vue-cli腳手架之webpack.prod.conf.js

webpack.prod.conf.js 生產環境配置文件:css

 

'use strict'//js嚴格模式執行
const path = require('path')//這個模塊是發佈到NPM註冊中心的NodeJS「路徑」模塊的精確副本
const utils = require('./utils')//utils.js文件
const webpack = require('webpack')//webpack模塊
const config = require('../config')//config文件夾下的index.js  是否是很神奇?
const merge = require('webpack-merge')//合併數組、對象爲一個新的對象的模塊
const baseWebpackConfig = require('./webpack.base.conf')//webpack.base.conf.js
const CopyWebpackPlugin = require('copy-webpack-plugin')//拷貝文件和文件夾模塊
const HtmlWebpackPlugin = require('html-webpack-plugin')//爲html文件中引入的外部資源(好比script/link等)動態添加每次compile後的hash,保證文件名不重複的好處是防止引用緩存文件致使修改暫未生效;可生成建立html入口文件
const ExtractTextPlugin = require('extract-text-webpack-plugin')//抽離css樣式,防止將樣式打包到js中引發加載錯亂
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')//壓縮css插件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//壓縮js代碼。

const env = require('../config/prod.env')//設置爲生產環境production
//merge方法合併模塊對象,在這個文件裏是將基礎配置webpack.base.conf.js和生產環境配置合併
const webpackConfig = merge(baseWebpackConfig, {
  module: {//模塊配置
    rules: utils.styleLoaders({//原版註釋Generate loaders for standalone style files (outside of .vue)生成獨立的樣式文件裝載機
      sourceMap: config.build.productionSourceMap,//設置sourceMap
      extract: true,//
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,//指定是否使用sourceMap
  output: {//指定輸出
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),//編譯輸出的js文件存放在js文件夾下,命名規則添加hash計算
    /**
     * 打包require.ensure方法中引入的模塊,若是該方法中沒有引入任何模塊則不會生成任何chunk塊文件
     *
     * 好比在main.js文件中,require.ensure([],function(require){alert(11);}),這樣不會打包塊文件
     * 只有這樣纔會打包生成塊文件require.ensure([],function(require){alert(11);require('./greeter')})
     * 或者這樣require.ensure(['./greeter'],function(require){alert(11);})
     * chunk的hash值只有在require.ensure中引入的模塊發生變化,hash值纔會改變
     * 注意:對於不是在ensure方法中引入的模塊,此屬性不會生效,只能用CommonsChunkPlugin插件來提取
     */
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({//壓縮js代碼的插件  具體能夠去npm查一下這個插件怎麼用以及能設置哪些參數
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,//是否生成sourceMap
      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: 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: ['.*']
      }
    ])
  ]//添加插件,是webpack功能更豐富
})
//是否容許壓縮?
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

 

 

關於開發環境和生產環境的區別,引用一段官網長的解釋。html

開發環境(development)生產環境(production)構建目標差別很大。在開發環境中,咱們須要具備強大的、具備實時從新加載(live reloading)或熱模塊替換(hot module replacement)能力的 source map 和 localhost server。而在生產環境中,咱們的目標則轉向於關注更小的 bundle,更輕量的 source map,以及更優化的資源,以改善加載時間。因爲要遵循邏輯分離,咱們一般建議爲每一個環境編寫彼此獨立的 webpack 配置。vue

雖然,以上咱們將生產環境開發環境作了略微區分,可是,請注意,咱們仍是會遵循不重複原則(Don't repeat yourself - DRY),保留一個「通用」配置。爲了將這些配置合併在一塊兒,咱們將使用一個名爲 webpack-merge 的工具。node

相關文章
相關標籤/搜索