Webpack 配置实践

splitChunks

默认配置

module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      automaticNameMaxLength: 30,
      name: true,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

说明:

  • splitChunks.cacheGroups下的每个属性对象,都会继承或覆盖splitChunks.*,但testpriorityreuseExistingChunksplitChunks.cacheGroups专有的属性

因此,对于vendors这个缓存组来说,实际上是这样的:

module.exports = {
  //...
  optimization: {
    // ...
    splitChunks: {
      // ...
      cacheGroups: {
        vendors: {
          chunks: 'async',
          minSize: 30000,
          maxSize: 0,
          minChunks: 1,
          maxAsyncRequests: 5,
          maxInitialRequests: 3,
          automaticNameDelimiter: '~',
          automaticNameMaxLength: 30,
          name: true,
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        }
        // ...
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  • chunks确定参与分离的chunk有哪些
  • test确定参与分离的chunk里的哪些模块会位于这个缓存组
  • name确定模块最终属于哪个split chunk

可以看到,splitChunks 的默认分组配置里,vendorsdefault分组的priority分别为-10-20,这是为了方便用户自定义的分组能够有更高的优先级(自定义分组的默认priority0)。