Bottom layer: webpack.prod.conf.js configuration file in the vue-cli scaffolding build directory

First statement: This article is excerpted from other people's documents, copied directly, so that you can view it yourself in the future, if there is any infringement, please understand

// The following is the path module that introduces nodejs
var path = require('path')
// The following is the utils tool configuration file, which is mainly used to process the loader of css class files
var utils = require('./utils')
// The following Introduce webpack to use the built-in webpack plugin
var webpack = require('webpack')
// The following is the index.js configuration file in the config directory, which is mainly used to define the relevant basic configuration of the production and development environment
var config = require(' ../config')
// The following is the merge plugin of webpack, which is mainly used to deal with the merging of configuration objects. You can split a large configuration object into several small ones, merge them, and the same items will override
var merge = require ('webpack-merge')
// Here is the webpack.base.conf.js config file, as explained in my other blog posts, loader for handling different types of files
var baseWebpackConfig = require('./webpack.base. conf')
// copy-webpack-plugin copies files or folders to the specified directory
var CopyWebpackPlugin = require('copy-webpack-plugin')
// html-webpack-plugin is to generate html files, and templates can be set
var HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin is used to separate the css and other files in the bundle to the specified .css file
var ExtractTextPlugin = require('extract-text- webpack-plugin')
// The function of the optimize-css-assets-webpack-plugin plugin is to compress the css code,
// it can also remove the duplicate code generated by the extract-text-webpack-plugin plugin to extract files,
//because the same A css may appear in multiple modules so it will lead to duplication of code, in other words, these two plugins are two brothers // For details, see (1)
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var ZipPlugin = require('zip-webpack-plugin')


//var env ={NODE_ENV: '"production"'}
var env = config.build.env
// merge current config object with base config object


var webpackConfig = merge(baseWebpackConfig, {
  module: {
// The following is to take the configuration configured by utils to handle various css types
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
// devtool development tool, used to generate a sourcemap for debugging,,, did not look carefully
  devtool: '#source-map',
  output: {
  // after packaging The file is placed in the dist directory
    path: config.build.assetsRoot,
  // The file name uses static/js/[name].[chunkhash].js, where name is the index, and chunkhash is the hash value of the module, which is used in the browser Cached
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
  // chunkFilename is a non-entry module file, which means chunkFilename is referenced in the filename file
    chunkFilename: utils.assetsPath('js/[ id].[chunkhash].js'),
    //publicPath: "https://cdn.chinaclear.cn/siteResource/pop-online-fund-vote-web/"
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
  // The following is to use the DefinePlugin plugin to define the process.env environment variable as env
    new webpack.DefinePlugin({
      'process.env' : env
    }),
// UglifyJsPlugin plugin is a new webpack specially used to compress js
    files.optimize.UglifyJsPlugin({
      compress: {
        //Do not output warnings when deleting useless code  
        warnings: false, // Disable warnings when compressing, Give the user a feeling that vue is tall and there is no mistake
        //delete the console statement
        drop_console: true
      },
      //delete the comments
      comments: false,
      mangle: false,
  // compress and generate a map file
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
    // Generate an independent css file, the following is the name of the generated independent css file
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      allChunks: true
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
    // compress css files
      cssProcessorOptions: {
        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


  // Generate html page
    new HtmlWebpackPlugin({
    //Generate index.html
      filename: config.build.index,
    // It doesn't matter if the template is index.html plus or not
      template: 'index.html',
      favicon: './src/assets/images/favicon.ico',
      excludeChunks: ['admin'] ,
      chunks: ['manifest','vue','ele','vendor','index'],
    // put the js file at the end of the body tag
      inject: true,
      minify: {
    // compressed output html page
        removeComments: false,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  // Categorize modules to be inserted into html pages
      chunksSortMode: 'manual'//'dependency'
    }),




    new HtmlWebpackPlugin({
      filename: config.build.adminIndex,
      template: 'admin.html',
      favicon: './static/img/favicon.ico',//'./src/assets/images/favicon.ico',
      excludeChunks: ['index'],
      chunks: ['manifest','vue','ele','vendor','admin'],
      inject: true,
      minify: {
        removeComments: false,
        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: 'manual' //'dependency'
    }),


    new webpack.HashedModuleIdsPlugin(),
    
    // split vendor js into its own file
// The following plugin extracts the third-party library files from the packaged file for convenience Browser cache to improve the running speed of the program


    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['index', 'admin'],
// Pack all the following files that depend on node_modules into vendor
      minChunks: function (module, count) {
        return (
          module.resource && 
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0 && 
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/element-ui')
          ) !== 0 &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue')
          ) !== 0 
        )
      }
    }),


    //分离element-ui
    new webpack.optimize.CommonsChunkPlugin({
        name: 'ele',
        filename: 'static/js/[name].[chunkhash].js',
        chunks: ['admin','index'] ,
        minChunks: function (module, count) {
          return (
            module.resource &&
            /\.js$/.test(module.resource) && 
            module.resource.indexOf(
              path.join(__dirname, '../node_modules/element-ui')
            ) === 0
          )
        }
    }),


    //分离vue组件
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vue',
      filename: 'static/js/[name].[chunkhash].js',
      chunks: ['index','admin'], 
      minChunks: function (module, count) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules/vue')
          ) === 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


// Extract the runtime code and module manifest code of webpack into the manifest file to prevent the problem of modifying the code but not modifying the third-party library files, causing the third-party library files to also be packaged


    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),


    // copy custom static assets
// The following is a plugin for copying files, I don't think it is here to copy files Instead, it filters out the files starting with . generated during the packaging process


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


    new ZipPlugin({
      path: path.join(__dirname,'../dist'),
      filename: 'dist.zip'
    })
  ]
})


if (config.build.productionGzip) {
// Turn on Gzi compressed and packaged files, do you know why this can still be compressed? ? , just like you packaged the compressed package, give this compressed package to the browser, and the browser will automatically decompress it 
// You must know that vue-cli disables this magical function by default, because Surge and Netlify static hosts help by default. You gzip the uploaded file
  var 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.  
// The packaged and compiled files print out detailed file information. vue-cli disables this by default. I think it is still useful. You can configure
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig. plugins.push(new BundleAnalyzerPlugin())
}


module.exports = webpackConfig

Advertise: Taobao Tmall internal discount group, add me to WeChat to pull you into the group 18801014156

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325597898&siteId=291194637
Recommended