推荐答案
// www.javascriptcn.com code example
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
},
};本题详细解读
chunks
- 作用: 指定哪些类型的代码块会被优化。
- 可选值:
'all': 所有代码块都会被优化。
'async': 只优化异步加载的代码块。
'initial': 只优化初始加载的代码块。
minSize
- 作用: 指定生成 chunk 的最小大小(以字节为单位)。
- 默认值:
30000(30KB)。
maxSize
- 作用: 指定生成 chunk 的最大大小(以字节为单位)。
- 默认值:
0(无限制)。
minChunks
- 作用: 指定一个模块被引用多少次才会被拆分到单独的 chunk 中。
- 默认值:
1。
maxAsyncRequests
- 作用: 指定按需加载时的最大并行请求数。
- 默认值:
5。
maxInitialRequests
- 作用: 指定入口点的最大并行请求数。
- 默认值:
3。
automaticNameDelimiter
- 作用: 指定生成 chunk 名称时使用的分隔符。
- 默认值:
'~'。
name
- 作用: 指定生成的 chunk 的名称。
- 可选值:
true: 自动生成名称。
false: 使用默认名称。
string: 自定义名称。
cacheGroups
- 作用: 定义缓存组,用于将模块分组到不同的 chunk 中。
- 配置项:
test: 匹配模块的路径或正则表达式。
priority: 优先级,数值越大优先级越高。
reuseExistingChunk: 是否重用已存在的 chunk。
vendors
- 作用: 专门用于处理
node_modules 中的模块。
- 配置项:
test: 匹配 node_modules 中的模块。
priority: 优先级设置为 -10,确保优先处理。
reuseExistingChunk: 重用已存在的 chunk。
default
- 作用: 默认的缓存组,用于处理其他模块。
- 配置项:
minChunks: 模块被引用至少 2 次才会被拆分。
priority: 优先级设置为 -20,低于 vendors。
reuseExistingChunk: 重用已存在的 chunk。