案例代碼以"webpack": "3.10.0","uglifyjs-webpack-plugin": "^1.3.0",為主
1.UglifyJsPlugin
webpack內置UglifyJsPlugin,壓縮和混淆代碼
new UglifyJsPlugin({
parallel: 4,
uglifyOptions: {
output: {
comments: false,
beautify: false,
},
compress: {
warnings: false
},
},
cache: true,
}), //壓縮代碼
2.CommonsChunkPlugin
webpack內置CommonsChunkPlugin,提高打包效率,將第三方庫和業務代碼分開打包。
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: "js/vendor.js",
children: true,
minChunks: Infinity,
}),
3.ProvidePlugin
ProvidePlugin:自動加載模塊,代替require和import
new webpack.ProvidePlugin({ //自動加載模塊
'$': "jquery",
'jQuery': "jquery",
'window.jQuery': "jquery",
'window.$': 'jquery'
}),
4.html-webpack-plugin
html-webpack-plugin可以根據模板自動生成html代碼,並自動引用css和js文件
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
5.extract-text-webpack-plugin
extract-text-webpack-plugin 將js文件中引用的樣式單獨抽離成css文件,防止將樣式打包在js中引起頁面樣式加載錯亂的現象
new ExtractTextPlugin({
filename:"css/index.css",
allChunks:false,
}),
6.DefinePlugin
DefinePlugin 編譯時配置全局變量,這對開發模式和發布模式的構建允許不同的行為非常有用。
7.HotModuleReplacementPlugin
HotModuleReplacementPlugin 熱更新
8.optimize-css-assets-webpack-plugin
optimize-css-assets-webpack-plugin 不同組件中重復的css可以快速去重
9.compression-webpack-plugin
compression-webpack-plugin 生產環境可采用gzip壓縮JS和CSS
new CompressionPlugin({ //打包文件為giz格式
filename: '[path].gz[query]', //目標資源名稱。[file] 會被替換成原資源。[path] 會被替換成原資源路徑,[query] 替換成原查詢字符串
algorithm: 'gzip',//算法
test: new RegExp('\\.(js|css)$'),
threshold: 10240,//只處理比這個值大的資源。按字節計算
minRatio: 0.8//只有壓縮率比這個值小的資源才會被處理
})
10.happypack
happypack:通過多進程模型,來加速代碼構建
11.CleanWebpackPlugin
重構之前刪除dist文件,除dist/img文件
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns:['**/*', '!img', '!img/**']
}),
