如何解决Webpack 4 SplitChunks,将异步块分组到一定大小
我们正在尝试优化我们的 webpack 捆绑。现在我们生成了很多小块,但我们想根据一些规则对它们进行分组:
- 节点模块和代码应该分开,例如。一个块要么是所有 node_modules 要么是所有代码
- 每个块大小应大于 20KB
- 我有点实现文件大小限制,但最终的问题是在第一页加载时,所有块都被一次下载,我拆分文件,因为我希望它们仅在需要时才被下载,不是一下子。以下是我为达到这一点所做的步骤。如果您能指出我正确的方式,我将不胜感激
1.现状
设置:
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[\\/]/,
3.所以现在这些小文件在我控制的那两个缓存组中,我尝试将它们分解成更小的文件
设置
optimization: {
splitChunks: {
...same as before...
cacheGroups: {
async_vendor: {
test: /[\\/]node_modules[\\/]/,maxSize: 200000,minSize: 200000,...same as before...
}
},
这看起来正是我想要的。只有一个问题是当我访问第一页时所有这些文件都被加载了。这在原始场景(1.)中不会发生。我怀疑这是因为我强制将名称放入 cacheGroup 中。但是如果我不强制命名,则会生成小块
4.如果我不指定缓存组名称会发生以下情况:(
设置
optimization: {
splitChunks: {
... same as before ...
cacheGroups: {
async_vendor: {
test: /[\\/]node_modules[\\/]/,... same as before ...
}
},
是否可以在 splitchunk 中解决这个问题?谢谢大家的帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。