1. 代码分割(Code Splitting)
通过代码分割,可以将代码拆分成多个较小的文件,实现按需加载,减少首屏加载时间。使用 SplitChunksPlugin
将公共代码提取到单独的 chunk 中,避免重复打包。
config.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
// 第三方组件
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/, //符合组的要求就给构建venders
priority: 10, //priority:优先级:数字越大优先级越高,因为默认值为0,所以自定义的一般是负数形式,决定cacheGroups中相同条件下每个组执行的优先顺序。
chunks: 'initial', // 仅限于最初依赖的第三方
},
elementUI: {
name: 'chunk-elementUI', // 将elementUI拆分为单个包
priority: 20, // 重量需要大于libs和app,否则将打包到libs或app中
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // 为了适应cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // 可以自定义规则
minChunks: 3, // 最小公共数
priority: 5,
reuseExistingChunk: true, //当前的chunk如果包含了从main里面分离出来的模块,则重用这个模块,这样的问题是会影响chunk的名称。
},
},
})
2. 压缩代码
使用 terser-webpack-plugin
压缩 JavaScript 代码,使用 css-minimizer-webpack-plugin
压缩 CSS 代码。
npm install terser-webpack-plugin css-minimizer-webpack-plugin --save-dev
// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin(),
new CssMinimizerPlugin()
]
}
};
3. 移除无用代码(Tree Shaking)
Tree Shaking 可以移除代码中未使用的部分,减少打包体积。确保你的代码使用 ES6 模块语法,并且在 package.json
中设置 "sideEffects": false
。
// package.json
{
"sideEffects": false
}
4.使用 IgnorePlugin
忽略不必要的模块
如果你使用了某些库(如 Moment.js),但不需要其所有语言包,可以使用 IgnorePlugin
忽略这些模块。
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/
})
5.优化 Source Map
在生产环境中,使用 cheap-module-source-map
或 source-map
来生成 Source Map,但要注意它们对构建性能的影响。
// 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
productionSourceMap: false,
6.多进程打包
使用 thread-loader
可以开启多进程打包,加快打包速度。
npm install thread-loader --save-dev
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
'thread-loader',
'babel-loader'
],
exclude: /node_modules/
}
]
}
};
7.使用 externals
排除外部依赖
如果你使用了 CDN 或其他方式引入外部库(如 jQuery),可以通过 externals
排除这些依赖,减少打包体积。
externals: {
jquery: 'jQuery'
}
8.排除不必要的文件
在 module.rules
中使用 exclude
选项排除不需要处理的文件,减少 Webpack 的处理负担。
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
}
};
9.优化图片和字体文件
-
使用
url-loader
或file-loader
处理图片和字体文件,并设置合适的limit
值。 -
使用
image-webpack-loader
压缩图片。
10.优化 babel-loader
配置
使用 include
和 exclude
来限制 babel-loader
的处理范围。
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
11.使用 esbuild-loader
替代 babel-loader
esbuild-loader
是一个基于 esbuild
的 loader,编译速度比 babel-loader
快很多。
module: {
rules: [
{
test: /\.js$/,
loader: 'esbuild-loader',
options: {
loader: 'jsx', // 如果需要支持 JSX
target: 'es2015' // 编译目标
}
}
]
}
总结
Webpack 性能优化涉及多个方面,包括减少文件搜索范围、代码分割、缓存、并行构建、Tree Shaking、压缩代码等。根据项目的具体情况,选择合适的优化策略,可以显著提升构建速度和减少打包体积。