对于大面积使用的第三方代码以及在业务中多次引用的业务代码需要进行抽离,避免在生产环境下浏览器重复请求加载。
一、配置代码分割
// webpack.prod.js
const { merge } = require('webpack-merge')
const webpackCommonConf = require('./webpack.common.js')
module.exports = merge(webpackCommonConf, {
// ...
optimization: {
// ...
// 分割代码块
splitChunks: {
chunks: 'all', // 一般使用all
/**
* initial 入口 chunk,对于异步导入的文件不处理
async 异步 chunk,只对异步导入的文件处理
all 全部 chunk
*/
// 缓存分组
cacheGroups: {
// 第三方模块
vendor: {
name: 'vendor', // chunk 名称
priority: 1, // 权限更高,优先抽离,重要!!!
test: /node_modules/,
minSize: 1024 * 30, // 大小限制 大于30kb才会进行抽离
minChunks: 1 // 最少复用过几次
},
// 公共的模块
common: {
name: 'common', // chunk 名称
priority: 0, // 优先级
minSize: 0, // 公共模块的大小限制
minChunks: 2 // 公共模块最少复用过几次
}
}
}
}
})
二、配置chunk引入
// webpack.common.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const srcPath = path.join(__dirname, '..', 'src')
module.exports = {
// ...
plugins: [
// ...
// 多入口 - 生成 index.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'index.html'),
filename: 'index.html',
// chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
chunks: ['index', 'vendor', 'common'] // 要考虑代码分割
}),
// 多入口 - 生成 other.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'other.html'),
filename: 'other.html',
chunks: ['other', 'common'] // 考虑代码分割
})
]
}