项目之前一直用webpack自带 UglifyJsPlugin 压缩,随着项目扩大,打包时间越来越长,于是着手优化缩短打包时间
方案一
替换为UglifyJsParallelPlugin插件,UglifyJsParallelPlugin支持多线程压缩,替换后打包时间缩短了3分之1
方式
1 安装 UglifyJsParallelPlugin插件
npm install --save-dev webpack-uglify-parallel
2 使用
var UglifyJsParallelPlugin = require('webpack-uglify-parallel');
new UglifyJsParallelPlugin({
workers: os.cpus().length,
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: true
})
方案二
利用webpack.DllPlugin 预打包,生成动态依赖库对重点内容不经常修改的库预打包生成依赖关系避免二次打包
1单独创建webpack.dll.config.js
var webpack = require('webpack');
var path = require('path');
var vendors = [
'react',
'react-dom'
];
var plugin = [
new webpack.DllPlugin({
path: path.join(__dirname, '/dll/manifest.json'),
name: '[name]',
context: __dirname
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false
}
})
];
module.exports = {
devtool: '#source-map',
entry: {
"vendors": vendors
},
output: {
path: path.join(__dirname, '/dll'),
filename: '[name].js',
library: '[name]',
libraryTarget: 'umd',
umdNamedDefine: true
},
plugins: plugin
};
2 执行webpack -p –progress –config webpack.dll.config.js 预打包
3 在webpack.config.js中引入打包生成的manifest.json
var manifest = require('./dll/manifest.json');
plugins: [
new webpack.DllReferencePlugin({
manifest,
}),
]
4 在页面中引入也编译生成的依赖库 vendors.js
推荐使用 add-asset-html-webpack-plugin插件动态注入
var AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
new AddAssetHtmlPlugin([
{
filepath: xxxxx,
outputPath: xxxxx,
publicPath: xxxxx
}
])
通过多线程压缩和预打包,打包时间大大缩短。
参考文章:http://engineering.invisionapp.com/post/optimizing-webpack/