Webpack 代码分割(Code Splitting)主要有三种方式:通过入口点、使用动态导入、通过 SplitChunksPlugin 配置公共依赖提取。
- 入口点分割
在 webpack.config.js 中配置多个入口,每个入口会生成单独的 bundle:
module.exports = {
entry: {
app: './src/app.js',
admin: './src/admin.js'
},
output: {
filename: '[name].[contenthash].bundle.js',
chunkFilename: '[name].[contenthash].chunk.js',
path: __dirname + '/dist'
}
};
- 动态导入
使用 import()语法或 require.ensure(旧版)实现按需加载:
// 按需加载模块
button.addEventListener('click', () => {
import('./math.js').then(module => {
console.log(module.add(1, 2));
});
});
- SplitChunksPlugin 优化
通过 optimization.splitChunks 配置提取公共依赖:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all', // 提取所有 chunk 的公共模块
minSize: 20000, // 最小体积(默认20KB)
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/, // 提取 node_modules 中的库
name: 'vendors',
priority: 10
},
commons: {
name: 'commons',
minChunks: 2, // 至少被两个 chunk 引用的模块
priority: 5
}
}
}
}
};
- 预加载/预获取
通过注释指令优化加载优先级:
// 预加载(高优先级)
import(/* webpackPreload: true */ './chart.js');
// 预获取(低优先级,空闲时加载)
import(/* webpackPrefetch: true */ './future-feature.js');
- 注意事项
使用 [contenthash]实现长效缓存。
动态导入的 chunk 默认按 id 命名,可通过 output.chunkFilename 自定义。
可通过 webpack-bundle-analyzer 分析包体积。
评论区