美文网首页
2020-06-17vue-cli项目之webpack打包(bu

2020-06-17vue-cli项目之webpack打包(bu

作者: 夏天的风2020 | 来源:发表于2020-06-18 16:03 被阅读0次

webpack打包vue-cli项目之webpack.prod.conf.js文件分析

'use strict'
//这个文件是打包过程汇总的核心文件,文件中声明的对象webpackConfig也是整个打包过程的核心对象
const path = require('path') //引入路径解析插件
const utils = require('./utils')//引入utils文件
const webpack = require('webpack')//引入webpack内置插件
const config = require('../config')//引入config文件
const merge = require('webpack-merge')//引入webpack-merge合并webpack配置对象
const baseWebpackConfig = require('./webpack.base.conf')//引入基本配置文件
const CopyWebpackPlugin = require('copy-webpack-plugin')//引入拷贝文件插件
const HtmlWebpackPlugin = require('html-webpack-plugin')//引入自动升成html模板插件
const ExtractTextPlugin = require('extract-text-webpack-plugin')//将bundle中的css等文件产出单独的bundle文件
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')//压缩css代码
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//丑化压缩js代码

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

    
//module也是一个对象,只有一个rules属性,rules属性的值是一个样式加载器的集合,用于加载各种样式
//(不同类型的样式文件如css/sass/scss需要使用不同的样式加载器)
//utils.styleLoaders是一个方法,实参是一个对象,这个对象里有三个布尔类型的属性,这些属性将
//会作为条件,选择性的创建所需的类加载器,并以集合的形式存储这些样式加载器。

//sourceMap : 代码转换前后的对应关系
//根据option是对象属性的布尔值作为条件,生成一个样式文件加载器的集合。
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap, 
      extract: true, //自定义项,设置为true表示,生成独立的文件
      usePostCSS: true
    })
  },

  devtool: config.build.productionSourceMap ? config.build.devtool : false,

  //output定义文件的输出路径及命名格式,
  output: {
    path: config.build.assetsRoot, //打包后的文件放在dist目录里面
    //文件名称使用static/js/[name].[chunkhash].js,其中name就是main,chunkhash就是模块的hash值,用于浏览器缓存的
    filename: utils.assetsPath('js/[name].[chunkhash].js'), 
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')//chunkFilename是非入口模块文件,也就是说filename文件引用了chunkFilename
  },

  //定义了一些会使用到的插件
  plugins: [
    new webpack.ProvidePlugin({
      'window.Quill': 'quill/dist/quill.js',
      Quill: 'quill/dist/quill.js'
    }),

    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    //DefinePlugin 这个插件用于定义当前的运行环境,来区分编译操作和打包操作。
    //env是从别的文件中导入的环境变量,这里的值表示的是打包操作.
    new webpack.DefinePlugin({
      'process.env': env
    }),

    //压缩js代码
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false //不显示警告信息
        }
      },
      sourceMap: config.build.productionSourceMap,//压缩后生成map文件(压缩前后的代码对应信息)
      parallel: true //并行提高效率,并行数量cpu的数量(默认为os.cpus().length-1,也可以说动指定数量)相关
    }),

    // extract css into its own file
    //ExtractTextPlugin这个插件的功能是将css文件提取到单独的文件中。
    //ExtractTextPlugin插件会将所有的*.css模块从entry chunk移动到一个单独的css文件中。
    //因此你的样式将不会再包含在js代码块中,而是在一个单独的css文件中(style.css)中。
    //由于加载css代码块和加载js代码块是并行操作的,因此这样做的效率更高,尤其是当你的样式表很大的时候。
    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

      //当使用`CommonsChunkPlugin`并且在公用的 chunk中有提取的chunk(来自`ExtractTextPlugin.extract`)时,
      //`allChunks`**必须设置为`true`
      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 }
    // }),

    //使用这个插件来优化、压缩css代码,解决使用extract-text-plugin可能会造成css重复的问题
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true,
        map: { inline: false },
        autoprefixer: { remove: false } // 添加对autoprefixer的配置
      }
    }),

    // 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
    //将产品文件的引用注入到index.html中
    new HtmlWebpackPlugin({
      filename:
        process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index,
      template: 'index.html',//模板文件,就是根目录里的那个文件。如果找不到与模板名相同的文件,则会报错
      inject: true,//将js文件放入到body标签的结尾(默认值),也可以选择插入到head中或者不插入
      favicon: path.resolve('./favicon.ico'),

      //minify的作用是对html文件进行压缩,minify的属性值是一个压缩选项或者false。
      //默认值是false,不对生成的html文件进行压缩
      minify: {
        removeComments: true, //删除index.html中的注释
        collapseWhitespace: true, //删除index.html中的空格
        removeAttributeQuotes: true//删除各种html标签属性值得双引号
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency' //确定script插入得顺序,dependency表示按照文件的依赖顺序进行处理
    }),

    // keep module.id stable when vendor modules does not change
    //浏览器的缓存机制会自动存储部分js代码,例如将第三方插件拆分成一个独立的chunk代码(vendor.js)。
    //由于一般我们不会修改第三方的代码,所以将第三方代码缓存起来会更高效。
    //但是chunk代码的名字中除了vendor还有一个哈希值,所以即使我们并没有修改第三方库中的代码,vendor chunk的名字还是会发生变化。
    //一旦发生变化,浏览器就会重新加载vendor chunk,这样的话,浏览器的缓存机制就形同虚设。
    //因此使用这个插件来解决这个。
    new webpack.HashedModuleIdsPlugin(),

    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),


    //CommonsChunkPlugin主要用来提取第三方库和公共模块,避免首屏加载的bundle文件或者按需加载的
    //bundle文件体积过大,从而导致加载时间过长,着实是优化的一把利器。
    //例如,2个js都引用了第三个js文件,不做提取的话,这个js文件就会被重复打包。
   

    //new webpack.optimize.CommonsChunkPlugin这个插件首先被用来提取第三方库。将所有从node_modules中
    //引入的js提取到vendor.js,同时便于浏览器缓存,提高程序的运行速度。
    //实参里没有指定chunks因此是从app.js(entry chunk)里面抽取代码,
    //同时没有指定filename,因此文件名取name中的vendor,下同。

    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) { //minChunks问函数,则根据返回值得逻辑来确定是否提取为common chunk。
        // any required modules inside node_modules are extracted to vendor
        //有正在处理文件+这个文件时.js后缀+这个文件是在node_modules中
        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: ['.*', 'ue/**', 'tinymce/**']
      }
    ])
  ]
})

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



原文链接:https://blog.csdn.net/qq_41948178/article/details/100688544

相关文章

网友评论

      本文标题:2020-06-17vue-cli项目之webpack打包(bu

      本文链接:https://www.haomeiwen.com/subject/yvwsxktx.html