通用配置
- 使用最新版本Webpack(V5版本的本地缓存)、Node
- 通过设置
resolve控制资源搜索范围 - 使用动态加载,减少首屏加载量
- 正确使用
[hash]命中缓存优化http资源请求效率 - 针对不需要编译的库设置
module.noParse跳过编译步骤 - 使用试验阶段功能
experiments.lazyCompilation只构建被使用的入口文件 source-map开发环境使用eval(最佳编译速度),生产环境使用source-map(最佳打包质量)- 通过设置
watchOptions.ignored指明不频繁更新的目录例如node_modules - 通过设置
module.rules.include和module.rules.exclude来约束Loader的执行搜索范围(会被打入生产包的除外) - 通过设置
ts-loader下的transpileOnly: true跳过typescript类型检查使用编辑器插件检查或使用fork-ts-checker-webpack-plugin将类型检测能力剥离到子进程 - 通过使用
eslint-webpack-plugin替代eslint-loader前者在模块构建完毕后执行检查,不会阻断文件加载流程性能更好
开发环境
- 开发模式禁用产物优化关闭
tree-shaking、splitChunks、minimizer提升开发环境下的构建性能
js
module.exports = {
// ...
mode: "development",
optimization: {
removeAvailableModules: false,
removeEmptyChunks: false,
splitChunks: false,
minimize: false,
concatenateModules: false,
usedExports: false
}
}
生产环境
在
optimization.minimizer中分别使用terser-webpack-plugin、css-minimizer-webpack-plugin、html-minifier-terser对对应文件进行压缩减少产出体积通过
webpack-analyzer分析后合理使用SplitChunks分包策略
js
module.exports = {
// ...
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
priority: -10,
name: "vendors",
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]/
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
name: 'default',
},
react: {
test: /(react|react-dom)/, // 匹配chunk的名称
name: 'react', //打包后的文件名
chunks: 'all',
priority: 13, // 优先级 越高则先处理
}
}
}
}
}