vue-cli腳手架之webpack.prod.conf.js
阿新 • • 發佈:2018-12-21
// An highlighted block
'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
關於開發環境和生產環境的區別,引用一段官網長的解釋。
開發環境(development)和生產環境(production)的構建目標差異很大
。
在開發環境中,我們需要具有強大的、具有實時重新載入(live reloading)或熱模組替換(hot module replacement)能力的 source map 和 localhost server。
而在生產環境中,我們的目標則轉向於關注更小的 bundle,更輕量的 source map,以及更優化的資源,以改善載入時間。
由於要遵循邏輯分離,我們通常建議為每個環境編寫彼此獨立的 webpack 配置。
雖然,以上我們將生產環境和開發環境做了略微區分,但是,請注意,我們還是會遵循不重複原則(Don't repeat yourself - DRY)
,保留一個“通用”配置
。為了將這些配置合併在一起,我們將使用一個名為 webpack-merge
的工具。