背景
当前端项目越来越大,webpack构建速度会越来越慢,基于此背景引发从技术角度对webpack构建速度优化
优化手段
- 缩小搜索范围
- IgnorePlugin
- noParse
- externals
- 缓存
- 多线程
缩小搜索范围
loader查找文件默认是全局搜索查找,优化loader查找文件范围,指定loader的作用目录或者需要排除的目录;通过配置使用include和exclude配置项,例如
{test: /\.jsx?$/,use: [{loader: 'babel-loader',options: {presets: ['@babel/preset-env', '@babel/react'],plugins: [[require('@babel/plugin-proposal-decorators'), { legacy: true }]],cacheDirectory: true, // 启用缓存},},],include: path.resolve(__dirname, 'src'),exclude: /node_modules/,
},
IgnorePlugin
大部门第三库内部会做国际化处理,包含很多语言包,而这些语言包对我们来说没有多大用,我们忽略掉这些语言包,可以提升构建速度,减少包体积
resourceRegExp表示要忽略的路径。contextRegExp表示要忽略的文件夹目录。
以moment为例
new webpack.IgnorePlugin(/./locale/, /moment/)
也可以写成
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
})
noParse
对于我们引入第三库,如jquery,这些包肯定不会依赖别的包,所以根本不需要webpack去解析它内部依赖关系,使用noParse进行忽略的模块文件中不会解析import,require等语法
module:{noParse:/jquery|lodash/
}
externals
externals配置项配置第三方库不打包bundle,因为每次打包的时候有些依赖变动很小,可以选择不打包进bundle,使用cdn引入,提升构建速度