从插件源码中可以看到,webpack-uglify-parallel的是实现原理是采用了多核并行压缩的方式来提升我们的压缩速度。
plugin.nextWorker().send({
input: input,
inputSourceMap: inputSourceMap,
file: file,
options: options
});
plugin._queue_len++;
if (!plugin._queue_len) {
callback();
}
if (this.workers.length < this.maxWorkers) {
var worker = fork(__dirname + '/lib/worker');
worker.on('message', this.onWorkerMessage.bind(this));
worker.on('error', this.onWorkerError.bind(this));
this.workers.push(worker);
}
this._next_worker++;
return this.workers[this._next_worker % this.maxWorkers];
使用配置也非常简单,只需要将我们原来webpack中自带的uglifyPlugin配置:
new webpack.optimize.UglifyJsPlugin({
exclude:/\.min\.js$/
mangle:true,
compress: { warnings: false },
output: { comments: false }
})
修改成如下代码即可:
const os = require('os');
const UglifyJsParallelPlugin = require('webpack-uglify-parallel');
new UglifyJsParallelPlugin({
workers: os.cpus().length,
mangle: true,
compressor: {
warnings: false,
drop_console: true,
drop_debugger: true
}
})
目前webpack官方也维护了一个支持多核压缩的UglifyJs插件:uglifyjs-webpack-plugin,使用方式类似,优势在于完全兼容webpack.optimize.UglifyJsPlugin中的配置,可以通过uglifyOptions写入,因此也做为推荐使用,参考配置如下:
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
new UglifyJsPlugin({
uglifyOptions: {
ie8: false,
ecma: 8,
mangle: true,
output: { comments: false },
compress: { warnings: false }
},
sourceMap: false,
cache: true,
parallel: os.cpus().length * 2
})
方案六、Tree-shaking & Scope Hoisting
wepback在2.X和3.X中从rolluo中借鉴了tree-shaking和Scope Hoisting,利用es6的module特性,利用AST对所有引用的模块和方法做了静态分析,从而能有效地剔除项目中的没有引用到的方法,并将相关方法调用归纳到了独立的webpack_module中,对打包构建的体积优化也较为明显,但是前提是所有的模块写法必须使用ES6 Module进行实现,具体配置参考如下:
// .babelrc: 通过配置减少没有引用到的方法
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}],
// https://www.zhihu.com/question/41922432
["es2015", {"modules": false}] // tree-shaking
]
}
// webpack.config: Scope Hoisting
{
plugins:[
// https://zhuanlan.zhihu.com/p/27980441
new webpack.optimize.ModuleConcatenationPlugin()
]
}
内容版权声明:除非注明,否则皆为本站原创文章。
