Vue-cli webpack.base.config.js解析

// 下面是引入nodejs的路徑模塊
var path = require('path')
// 下面是utils工具配置文件,主要用來處理css類文件的loader
var utils = require('./utils')
// 下面引入webpack,來使用webpack內置插件
var webpack = require('webpack')
// 下面是config目錄下的index.js配置文件,主要用來定義了生產和開發環境的相關基礎配置
var config = require('../config')
// 下面是webpack的merger插件,主要用來處理配置對象合併的,
// 能夠將一個大的配置對象拆分紅幾個小的,合併,相同的項將覆蓋
var merge = require('webpack-merge')
// 下面是webpack.base.conf.js配置文件,我其餘博客文章已經解釋過了,用來處理不一樣類型文件的loader
var baseWebpackConfig = require('./webpack.base.conf')
// copy-webpack-plugin複製文件或者文件夾到指定的目錄的
var CopyWebpackPlugin = require('copy-webpack-plugin')
// html-webpack-plugin是生成html文件,能夠設置模板
var HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin這個插件是用來將bundle中的css等文件分離到指定.css文件
var ExtractTextPlugin = require('extract-text-webpack-plugin')
// optimize-css-assets-webpack-plugin插件的做用是壓縮css代碼的,
//還能去掉extract-text-webpack-plugin插件抽離文件產生的重複代碼,
//由於同一個css可能在多個模塊中出現因此會致使重複代碼,換句話說這兩個插件是兩兄弟 // 詳情見(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
// 把當前的配置對象和基礎的配置對象合併
var webpackConfig = merge(baseWebpackConfig, {
  module: {
// 下面就是把utils配置好的處理各類css類型的配置拿過來
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
// devtool開發工具,用來生成個sourcemap方便調試,,,沒仔細看
  devtool: '#source-map',
  output: {
  // 打包後的文件放在dist目錄裏面
    path: config.build.assetsRoot,
  // 文件名稱使用 static/js/[name].[chunkhash].js, 
       // 其中name就是index,chunkhash就是模塊的hash值,用於瀏覽器緩存的
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
  // chunkFilename是非入口模塊文件,也就是說filename文件中引用了chunckFilename
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'),
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
  // 下面是利用DefinePlugin插件,定義process.env環境變量爲env
    new webpack.DefinePlugin({
      'process.env': env
    }),

    // UglifyJsPlugin插件是專門用來壓縮js文件的
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        // 刪除無用代碼時不輸出警告 
        warnings: false, // 禁止壓縮時候的警告信息,給用戶一種vue高大上沒有錯誤的感受
        // 刪除console語句
        drop_console: true
      },
      // 刪除註釋
      comments: false,
      mangle: false,
      // 壓縮後生成map文件
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      // 生成獨立的css文件,下面是生成獨立css文件的名稱
      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
      // vue-cli 2.6.0 在啓用CommonsChunkPlugin插件後該選項會形成打包報錯‘ref-5-2’
      allChunks: true
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      // 壓縮css文件
      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

    // 生成html頁面
    new HtmlWebpackPlugin({
      // 生成index.html
      filename: config.build.index,
      // 模板是index.html加不加無所謂
      template: 'index.html',
      favicon: './src/assets/images/favicon.ico',
      excludeChunks: ['admin'],
      chunks: ['manifest','vue','ele','vendor','index'],
      // 將js文件放到body標籤的結尾
      inject: true,
      minify: {
        // 壓縮產出後的html頁面
        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
      // 分類要插到html頁面的模塊
      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
    // 下面的插件是將打包後的文件中的第三方庫文件抽取出來,
    // 便於瀏覽器緩存,提升程序的運行速度

    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['index', 'admin'],
      // 將全部依賴於node_modules下面文件打包到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

    // 把webpack的runtime代碼和module manifest代碼提取到manifest文件中,
    // 防止修改了代碼可是沒有修改第三方庫文件致使第三方庫文件也打包的問題

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

    // copy custom static assets
    // 下面是複製文件的插件,我認爲在這裏並非起到複製文件的做用,
    // 而是過濾掉打包過程當中產生的以.開頭的文件

    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) {
// 開啓Gzi壓縮打包後的文件,老鐵們知道這個爲何還能壓縮嗎??
// 就跟你打包壓縮包同樣,把這個壓縮包給瀏覽器,瀏覽器自動解壓的 
// 你要知道,vue-cli默認將這個神奇的功能禁用掉的,
// 理由是Surge 和 Netlify 靜態主機默認幫你把上傳的文件gzip了
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      // 這裏compression-webpack-plugin版本爲1.X,
      // 若是是2.X版本須要將asset替換成filename,否則會報錯
      // 2.X版本 Requirements:This module requires a minimum of Node v6.9.0 and Webpack v4.0.0
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}



if (config.build.bundleAnalyzerReport) {  
// 打包編譯後的文件打印出詳細的文件信息,vue-cli默認把這個禁用了,我的以爲仍是有點用的,能夠自行配置
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

複製代碼

額外說明:javascript

在小於webpack4.x版本中compression-webpack-plugin插件運行會報下圖中的錯誤,這是因爲本地安裝的compression-webpack-plugin是2.X版本,官方說明:css

Requirements:This module requires a minimum of Node v6.9.0 and Webpack v4.0.0
複製代碼

因此解決方案很簡單,將compression-webpack-plugin卸載,並安裝1.X版本便可,若是非要用2.X版本請將webpack升級到4.X版本 報錯信息html

相關文章
相關標籤/搜索