npm run build执行的操作

...
"scripts":{
	//执行build/build.js文件
	"build":"node build/build.js" 
}
build.js
'use strict'
//执行check-version.js文件
require('./check-versions')()

process.env.NODE_ENV = 'production'
//进度转轮,用于node的控制台进度美化,https://www.npmjs.com/package/ora
const ora = require('ora')
//以包的形式包装rm -rf命令,用来删除文件和文件夹,不管文件夹是否为空,都可删除
const rm = require('rimraf')
//引入path模块
const path = require('path')
// 引入chalk模块 修改控制台中字符串的样式
const chalk = require('chalk')
// 引入webpack
const webpack = require('webpack')
// 引入config/index文件
const config = require('../config')
// 引入webpack.prod.conf.js文件
const webpackConfig = require('./webpack.prod.conf')
//设置转轮后方的文字
const spinner = ora('building for production...')
//运行转轮,有text则显示text
spinner.start()
//删除对应文件夹后执行函数
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  // 执行webpackConfig
  webpack(webpackConfig, (err, stats) => {
    //停止转轮并清除文字
    spinner.stop()
    if (err) throw err
    //process.stdout标准输出流(终端显示)
    process.stdout.write(stats.toString({
      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'
    ))
  })
})

webpack.prod.conf.js
'use strict'
// 引入path模块
const path = require('path')
//引入utils.js文件,设置css模块loader
const utils = require('./utils')
// 引入webpack
const webpack = require('webpack')
// 引入config/index.js
const config = require('../config')
// 引入webpack-merge合并配置文件,webpack-merge合并配置文件时,允许链接数组并合并对象,而不是覆盖组合
const merge = require('webpack-merge')
引入webpack.base.conf.js文件,文件中设置了基础的context、entry、module和node
const baseWebpackConfig = require('./webpack.base.conf')
//webpack拷贝插件,将文件拷贝到指定的目标文件夹
const CopyWebpackPlugin = require('copy-webpack-plugin')
//用于创建一个在body中使用script包含了所有webpack包的HTML5文件
const HtmlWebpackPlugin = require('html-webpack-plugin')
//用于抽离CSS样式,防止将样式打包在js中引起页面样式加载错乱的问题
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 用于压缩以及合并重复的CSS
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 用于压缩优化js文件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// 引用prod.env.js文件
const env = require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    //引入所有的样式处理loader
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      //引入vue-style-loader
      extract: true,
      //引入postCssLoader
      usePostCSS: true
    })
  },
  //生成source-map类型的map文件,便于查找问题
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    //输出到dist文件夹
    path: config.build.assetsRoot,
    //设置每个输出bundle的名称
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    //设置非入口模块文件的名称,非入口模块是指入口文件(filename)引入的文件
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    //创建一个在编译时可以配置的全局变量
    new webpack.DefinePlugin({
      'process.env': env
    }),
    //压缩优化js文件
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false //禁止压缩时候的警告信息
        }
      },
      //是否生成压缩后的map文件
      sourceMap: config.build.productionSourceMap,
      //是否启用并行化
      parallel: true
    }),
    // extract css into its own file
    //提取css文件
    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
      // 设置从所有的chunk中提取css
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    //压缩css文件
    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
    // 生成一个HTML5文件,使用script标签引入webpack包
    new HtmlWebpackPlugin({
      // 写入HTML文件的位置和名字
      filename: config.build.index,
      // HTML文件的模板
      template: 'index.html',
      // webpack包引入的位置
      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
    //根绝模块的相对路径生成四位数的hash作为模块的id
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    //启动作用域提升
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    //提取node_model
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          //module.resource 文件的路径
          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
    // 提取webpack引导逻辑
    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: ['.*']
      }
    ])
  ]
})
//是否启动gzip压缩
if (config.build.productionGzip) {
  //引入压缩插件,提供带有Content-Encoding编码的压缩版的资源
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      //目标资源名称 file替换成原资源 path替换成原资源路径 query替换成原查询字符串
      asset: '[path].gz[query]',
      //设置压缩算法
      algorithm: 'gzip',
      //处理所有匹配此RegExp的资源
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      //设置限制,只处理比这个值大的资源
      threshold: 10240,
      //设置压缩率,只有比这个值小的资源才会被处理
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  //引入插件,读取输出文件夹中的stats.json文件,将文件可视化,用来比较bundle文件的大小
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

引用的文件在这里:
utils.js学习
webpack.base.conf.js学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值