Webpack:如何将CommonsChunkPlugin(wp3)迁移到Optimization.splitChunks(wp4)?

时间:2018-08-08 05:29:25

标签: webpack webpack-4 webpack-3 commonschunkplugin

我正试图从3迁移到webpack4,而迁移CommonsChunkPlugin确实很困难。

在WP3上,我具有以下简化配置:

const entries = {
  client: './src/index.js',
  common1: ['lodash'],
  common2: ['react', 'react-dom']
};

module.exports = {
  ...
  entry: entries,
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['common1', 'common2'],
      minChunks: Infinity
    })
  ]
};

在WP4上,我已经尝试使用optimization.splitChunks进行多种组合,但是我无法使它们正确地捆绑我的模块,使其共享共同的依赖关系,就像以前在WP3上一样。 / p>

这是我上次尝试使用的内容,但是最终的捆绑包的尺寸要大得多:

// same entries object
const entries = { ... };

module.exports = {
  ...
  entry: entries,
  optimization: {
    splitChunks: {
    minChunks: Infinity,
    chunks: 'initial',
    cacheGroups: {
      common1: { test: 'common1' },
      common2: { test: 'common2' },
      // disables the default definition of these cache groups
      vendors: false, 
      default: false
    }
  }
};

1 个答案:

答案 0 :(得分:0)

您可以简单地设置enforce = true,这将“强制” webpack始终 为缓存组创建块。

如果要进行代码拆分(使用import()),则需要设置chunks = "all",因为使用"initial"时,您只是将同步模块分组。

最后,如果组“ common1”和“ common2”可能共享任何模块,则可以考虑为一个高速缓存组赋予更高的优先级,例如,如果“ common1”可能首先被加载,此优先级应该更高,这样就不必下载“ common2”作为依赖项。

一些有用的链接可以帮助使这些内容神秘化:

  1. https://medium.com/dailyjs/webpack-4-splitchunks-plugin-d9fbbe091fd0
  2. https://webpack.js.org/plugins/split-chunks-plugin
  3. https://stackoverflow.com/a/49213048/2039244

module.exports = {
  ...
  entry: entries, // entries -> entry
  optimization: {
    splitChunks: {
      cacheGroups: {
        common1: {
          test: 'common1',
          chunks: 'all',
          enforce: true
        },
        common2: {
          test: 'common2',
          chunks: 'all',
          enforce: true
        },
        // disables the default definition of these cache groups
        vendors: false, 
        default: false
      }
    }
};