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
      }
    }
  },},

enter image description here

可以看到有很多小文件

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[\\/]/,

enter image description here

没有更多的小文件,所以小文件是异步块

3.所以现在这些小文件在我控制的那两个缓存组中,我尝试将它们分解成更小的文件

设置

optimization: {
  splitChunks: {
    ...same as before...
    cacheGroups: {
      async_vendor: {
        test: /[\\/]node_modules[\\/]/,maxSize: 200000,minSize: 200000,...same as before...
    }
  },

enter image description here

这看起来正是我想要的。只有一个问题是当我访问第一页时所有这些文件都被加载了。这在原始场景(1.)中不会发生。我怀疑这是因为我强制将名称放入 cacheGroup 中。但是如果我不强制命名,则会生成小块

enter image description here

4.如果我不指定缓存组名称会发生​​以下情况:(

设置

optimization: {
  splitChunks: {
    ... same as before ...
    cacheGroups: {
      async_vendor: {
        test: /[\\/]node_modules[\\/]/,... same as before ...
    }
  },

Situation 4

是否可以在 splitchunk 中解决这个问题?谢谢大家的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)