我们正在尝试优化我们的 webpack 捆绑。现在我们生成了很多小块,但我们想根据一些规则对它们进行分组:
- 节点模块和代码应该分开,例如。一个块要么是所有 node_modules 要么是所有代码
- 每个块大小应大于 20KB
- 我有点实现文件大小限制,但最终的问题是,在第一页加载时,所有块都一次下载,我拆分文件是因为我希望它们仅在需要时才下载,而不是全部立刻。以下是我为达到这一点所做的步骤。如果你能指出我正确的方式,那将不胜感激
一、现状
设置:
optimization: {
splitChunks: {
chunks: 'all', // optimize both static and dynamic import
maxAsyncRequests: 5, // for each additional load no more than 5 files at a time
maxInitialRequests: 3, // each entrypoint should not request more then 3 js files
automaticNameDelimiter: '~', // delimeter for automatic naming
automaticNameMaxLength: 30, // length of name
name: true, // let webpack calculate name
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
enforce: true // seperate vendor from our code
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
},
2.为了了解小块的来源,我强制将异步块合并为两个,一个来自node_modules,一个来自代码
环境
optimization: {
splitChunks: {
... same as before ...
cacheGroups: {
async_vendor: {
test: /[\\/]node_modules[\\/]/,
chunks: "async",
priority: 20,
name:"async_vendor",
},
async_code: {
chunks: "async",
priority: 10,
name: "async_code",
},
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
enforce: true // seperate vendor from our code
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
},
3.所以现在这些小文件在我控制那两个缓存组中,我尝试将它们分成更小的文件
环境
optimization: {
splitChunks: {
...same as before...
cacheGroups: {
async_vendor: {
test: /[\\/]node_modules[\\/]/,
chunks: "async",
priority: 20,
name:"async_vendor",
maxSize: 200000,
minSize: 200000,
},
async_code: {
chunks: "async",
priority: 10,
name: "async_code",
maxSize: 200000,
minSize: 200000,
},
...same as before...
}
},
},
这看起来正是我想要的。只有一个问题是当我访问第一页时所有这些文件都被加载了。这在原始场景中不会发生(1.)。我怀疑这是因为我将名称强制放入 cacheGroup。但如果我不强制命名,则会生成小块
4.如果我不指定缓存组名称会发生什么:(
环境
optimization: {
splitChunks: {
... same as before ...
cacheGroups: {
async_vendor: {
test: /[\\/]node_modules[\\/]/,
chunks: "async",
priority: 20,
name:"async_vendor",
maxSize: 200000,
minSize: 200000,
},
async_code: {
chunks: "async",
priority: 10,
maxSize: 200000,
minSize: 200000,
},
... same as before ...
}
},
},
是否有可能在 splitchunk 中解决这个问题?谢谢你的帮助