Webpack 优化方案
约 467 字大约 2 分钟
2024-08-14
构建性能优化
1. 减少解析范围
// webpack.config.js
module.exports = {
resolve: {
// 只解析这些扩展名,减少查找
extensions: ['.js', '.jsx', '.json'],
// 路径别名,减少查找
alias: {
'@': path.resolve(__dirname, 'src'),
'components': path.resolve(__dirname, 'src/components')
},
// 排除 node_modules,减少搜索
modules: [path.resolve(__dirname, 'src'), 'node_modules']
}
};2. 使用 DllPlugin 优化构建速度
// webpack.dll.config.js
module.exports = {
entry: {
vendor: ['react', 'react-dom', 'lodash']
},
output: {
filename: '[name].dll.js',
path: path.resolve(__dirname, 'dll'),
library: '[name]'
},
plugins: [
new webpack.DllPlugin({
name: '[name]',
path: path.resolve(__dirname, 'dll/[name].manifest.json')
})
]
};3. 开启缓存
module.exports = {
cache: {
type: 'filesystem', // 持久化缓存
buildDependencies: {
config: [__filename]
}
}
};输出体积优化
1. Tree Shaking
// 在 package.json 中标记为 sideEffect-free
{
"sideEffects": false
}
// 或指定有副作用的文件
{
"sideEffects": ["./src/styles/*.css"]
}2. 代码分割(Code Splitting)
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: 10
},
common: {
minChunks: 2,
priority: 5,
reuseExistingChunk: true
}
}
}
}
};3. 压缩
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 移除 console
drop_debugger: true
}
}
}),
new CssMinimizerPlugin()
]
}
};4. 动态导入
// 路由懒加载
const Home = () => import(/* webpackChunkName: "home" */ './Home');
const About = () => import(/* webpackChunkName: "about" */ './About');
// 组件懒加载
const HeavyComponent = () => import('./HeavyComponent');
// 条件加载
async function getCondition() {
if (condition) {
return import('./feature-a');
}
return import('./feature-b');
}运行性能优化
1. 长缓存优化
module.exports = {
output: {
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].chunk.js'
}
};2. 预取/预加载
// 预取:空闲时加载
import(/* webpackPrefetch: true */ './Component');
// 预加载:当前模块加载完成后立即加载
import(/* webpackPreload: true */ './Component');监控与分析
1. 构建分析
// webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};2. 速度分析
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
// webpack config
});生产环境优化
// webpack.prod.config.js
module.exports = merge(baseConfig, {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: true,
minimize: true,
splitChunks: {
chunks: 'all',
cacheGroups: {
defaultVendors: {
reuseExistingChunk: true
},
default: {
reuseExistingChunk: true,
minChunks: 2
}
}
}
},
performance: {
hints: 'warning',
maxEntrypointSize: 512000,
maxAssetSize: 512000
}
});参考文章:
