上篇说到了happypack可以让webpack分成多个子进程去打包代码,然后再将结果返回给主进程,其实压缩代码的时候也可以使用多进程,这样也可以提高构建速度,而webpack-parallel-uglify-plugin就做到了这一点
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const HappyPack=require('happypack');
const ParallelUglifyPlugin=require('webpack-parallel-uglify-plugin');
module.exports={
entry:'./main.js',
output:{
path:path.resolve(__dirname,'./dist'),
filename:'bundle.js'
},
module:{
rules:[{
test:/\.css$/,
use: ['happypack/loader?id=css']
},
{
test:/\.js$/,
use:['happypack/loader?id=babel'],
exclude:path.resolve(__dirname,'node_modules')
},
{test:/\.jpg$/,
loader:'url-loader',
options:{limit:3*1034,callback:'file-loader'}
},
{test:/\.html$/,
loader:'html-loader'}
]
},
devServer:{hot:true,
host:'127.0.0.1',
port:4000,
open:true,
compress:true,
historyApiFallback:true
},
plugins:[new HtmlWebpackPlugin({template:'./index1.html'}),
new HappyPack({id:'babel',loaders:['babel-loader?cacheDirectory']}),
new HappyPack({id:'css',loaders:['style-loader','css-loader']}),
new ParallelUglifyPlugin({
uglifyJS:{output:{
beautify:false, //最紧凑的输出
comments:false //删除注释
},
compress:{
drop_console:true, //删除所有输出语句
collapse_vars:true, //内嵌已定义但只用到一次的变量
reduce_vars:true //提取出出现多次但是没有定义成变量去引用的静态值
}
}
})
],
mode:'development'
}
使用ParallelUglifyPlugin实例化时还可以传几个参数
test:使用正则去匹配哪些文件需要被ParallerUglifyPlugin压缩,默认是/.js$/,也就是默认匹配所有js文件
include:作用和test一样,默认是为[]
exclude:匹配哪些文件不需要被ParallerUglifyPlugin压缩
cacheDir:缓存压缩的结果,下次遇到一样的压缩直接从缓存中取就可以了,默认是不开启,可以配置缓存的路径
workerCount:配置需要几个子进程去并发执行压缩,默认是当前cpu核数-1
sourceMap:是否生成映射文件
uglifyJs:用于压缩es5代码时配置,为object类型
uglifyEs:用于压缩es6代码时配置,为object类型