vue项目结构及文件介绍(2) —— build文件夹

在这里插入图片描述
build文件夹里面是对 webpack 开发和打包的相关设置,包括入口文件、输出文件、使用的模块等;

build.js文件

构建环境下的配置:
loading动画、删除创建目标文件夹、webpack编译、输出信息

'use strict' // js的严格模式
require('./check-versions')() // node和npm的版本检查

process.env.NODE_ENV = 'production' // 设置环境变量为生产环境

// 导进各模块
const ora = require('ora') // loading模块
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')

const spinner = ora('building for production...')
spinner.start()

// rm方法删除dist/static文件夹
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err //若删除中有错误则抛出异常并终止程序
  webpack(webpackConfig, (err, stats) => { //若没有错误则继续执行,构建webpack
    spinner.stop() //结束loading动画
    if (err) throw err //若有异常则抛出
    process.stdout.write(stats.toString({ //标准输出流,类似于console.log
      colors: true, // 增加控制台颜色开关
      modules: false, // 是否增加内置模块信息
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false, // 允许较少的输出
      chunkModules: false // 编译过程持续打印
    }) + '\n\n')

    // 编译出错的信息
    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }
    // 编译成功的信息
    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})
check-versions.js文件

node和npm的版本检查

'use strict' // js的严格模式

// 导进各模块
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs') // shell.js插件,执行unix系统命令


function exec (cmd) {
   // 脚本可以通过child_process模块新建子进程,从而执行Unix系统命令
   // 将cmd参数传递的值转换成前后没有空格的字符串,也就是版本号
 return require('child_process').execSync(cmd).toString().trim()
}

//声明常量数组,数组内容为有关node相关信息的对象
const versionRequirements = [
 {
   name: 'node',                                   //对象名称为node
   currentVersion: semver.clean(process.version),  //使用semver插件,把版本信息转换成规定格式
   versionRequirement: packageConfig.engines.node  //规定package.json中engines选项的node版本信息
 }
]

if (shell.which('npm')) {                       //which为linux指令,在$path规定的路径下查找符合条件的文件
 versionRequirements.push({
   name: 'npm',                                
   currentVersion: exec('npm --version'),        //调用npm --version命令,并且把参数返回给exec函数获取纯净版本
   versionRequirement: packageConfig.engines.npm //规定package.json中engines选项的node版本信息
 })
}

module.exports = function () {
 const warnings = []

 for (let i = 0; i < versionRequirements.length; i++) {
   const mod = versionRequirements[i]
   // 如果版本号不符合package.json文件中指定的版本号,就执行warning.push...
   // 当前版本号用红色标识,要求版本号用绿色标识
   if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
     warnings.push(mod.name + ': ' +
       chalk.red(mod.currentVersion) + ' should be ' +
       chalk.green(mod.versionRequirement)
     )
   }
 }

 //如果为真,则打印提示用户升级新版本
 if (warnings.length) {
   console.log('')
   console.log(chalk.yellow('To use this template, you must update following to modules:'))
   console.log()

   for (let i = 0; i < warnings.length; i++) {
     const warning = warnings[i]
     console.log('  ' + warning)
   }

   console.log()
   process.exit(1)
 }
}
utils.js文件

配置静态资源路径;
生成cssLoaders用于加载.vue文件中的样式;
生成styleLoaders用于加载不在.vue文件中的单独存在的样式文件

'use strict'
const path = require('path')
const config = require('../config')             // 引入config下的index.js文件
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 一个插件,抽离css样式,防止将样式打包在js中引起样式加载错乱
const packageConfig = require('../package.json')
const packageConfig = require('../package.json')

// 导出assetsPath
exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path) // path.join返回绝对路径(在电脑上的实际位置);path.posix.join返回相对路径
}

exports.cssLoaders = function (options) {
  options = options || {}

  const cssLoader = {
    loader: 'css-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        publicPath:'../../',
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)

  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }

  return output
}

exports.createNotifierCallback = () => {
  const notifier = require('node-notifier')

  return (severity, errors) => {
    if (severity !== 'error') return

    const error = errors[0]
    const filename = error.file && error.file.split('!').pop()

    notifier.notify({
      title: packageConfig.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      icon: path.join(__dirname, 'logo.png')
    })
  }
}
vue-loader.conf.js文件
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production' // 是否为生产环境
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

module.exports = {
  loaders: utils.cssLoaders({   // 载入utils中的cssloaders返回配置好的css-loader和vue-style=loader
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled, // 是否开启css资源map
  cacheBusting: config.dev.cacheBusting, // 是否开启cacheBusting
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}
webpack.base.conf.js文件

基本的webpack配置
  配置webpack编译入口
  配置webpack输出路径和命名规则
  配置模块resolve规则
  配置不同类型模块的处理规则

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
const vuxLoader = require('vux-loader')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}



let webpackConfig = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  externals:{
    'BMap':'BMap',
    'BMap_Symbol_SHAPE_POINT': 'BMap_Symbol_SHAPE_POINT'
  },
  output: {
    path: config.build.assetsRoot, // 打包后文件输出路径,config/index.js中build.assetsRoot
    filename: '[name].js', // 输出文件名称默认使用原名
    publicPath: process.env.NODE_ENV === 'production' // 文件引用路径
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'], // 省略扩展名,也就是说当使用.js .vue .json文件导入可以省略后缀名
    alias: {
      'vue$': 'vue/dist/vue.esm.js', // $符号指精确匹配,路径和文件名要详细
      '@': resolve('src'), // resolve('src') 指的是项目根目录中的src文件夹目录,使用@符号代替
    }
  },
  // 用于解析不同的模块
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader', // 解析.vue文件
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader', // 对js文件使用babel-loader转码,用于解析es6等代码
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] // 指明那些文件夹下的js文件需要使用该loader
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader', // 使用url-loader插件,将图片转为base64格式字符串
        options: {
          limit: 10000, // 10000个字节以下的文件才用来转为dataUrl
          name: utils.assetsPath('img/[name].[hash:7].[ext]') //超过10000字节的图片,就按照制定规则设置生成的图片名称,可以看到用了7hash码来标记,.ext文件是一种索引式文件系统
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}
module.exports = vuxLoader.merge(webpackConfig,{
  plugins:['vux-ui']
})
webpack.dev.conf.js文件

开发环境配置
  在base.conf基础进一步完善
  将hot-reload相关的代码添加到entry chunks
  使用styleLoaders
  配置Source Maps
  配置webpack插件

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 一个用于生成HTML文件并自动注入依赖文件(link/script)的webpack插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // 用于更友好地输出webpack的警告、错误等信息
// 获取port
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

/*
    合并基础的webpack配置
        第一个参数baseWebpackConfig,是webpack基本配置文件webpack.base.conf.js中的配置
*/
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true, // 是否启用webpack的模块热替换特性。主要是用于开发过程中
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true, // 一切服务是否都启用gzip压缩
    host: HOST || config.dev.host, // 指定一个host,默认是localhost。如果有全局host就用全局,否则就用index.js中的设置。
    port: PORT || config.dev.port, // 指定端口
    open: config.dev.autoOpenBrowser, // 是否在浏览器开启本dev server
    overlay: config.dev.errorOverlay // 当有编译器错误时,是否在浏览器中显示全屏覆盖
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable, // 代理:如果你有单独的后端开发服务器api,并且希望在同域名下发送api请求,那么代理某些URL会很有用
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll, // 是否使用轮询
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})
webpack.prod.conf.js文件

生产环境配置
  在base.conf基础进一步完善
  合并基础webpack配置
  使用styleLoaders
  配置webpack输出
  配置webpack插件
  gzip模式下的webpack插件配置
  webpack-bundle分析

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : require('../config/prod.env')

// 合并基础的webpack配置
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  // 配置webpack输出
  output: {
    path: config.build.assetsRoot, // 编译输出目录
    filename: utils.assetsPath('js/[name].[chunkhash].js'), // 编译输出文件名格式
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') // 没有指定输出名的文件输出的文件名格式
  },
   // 配置webpack插件
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
  • 22
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
回答: 一个Vue项目文件夹通常包含以下内容: 1. src文件夹:这是项目的主要源代码文件夹,包含Vue组件、样式文件、图片等资源。 2. public文件夹:这是一个静态资源文件夹,其中的文件会被直接复制到最终的构建目录中。通常用于存放不需要经过编译的静态文件,比如index.html文件。 3. node_modules文件夹:这是存放项目依赖的文件夹,其中包含了项目所需的各种第三方库和插件。 4. dist文件夹:这是构建后的项目文件夹,其中包含了经过编译和打包后的最终代码。通常用于部署到服务器上。 5. vue.config.js文件:这是一个可选的配置文件,用于配置Vue项目的一些构建和开发选项。如果存在这个文件,@vue/cli-service会自动加载它。 6. package.json文件:这是一个描述项目的配置文件,其中包含了项目的名称、版本号、依赖等信息。还可以在这个文件中定义一些脚本命令,用于执行各种开发和构建任务。 除了上述文件夹文件,还可以根据项目的需要添加其他文件夹文件。例如,可以添加一个components文件夹用于存放Vue组件,或者添加一个assets文件夹用于存放项目的静态资源。总之,文件夹的组织结构可以根据项目的规模和需求进行调整。\[1\] #### 引用[.reference_title] - *1* *2* *3* [vue项目文件介绍](https://blog.csdn.net/xm1037782843/article/details/98469489)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值