首页 > 解决方案 > Webpack Split Chunks Plugin 覆盖 cacheGroups,正则表达式匹配错误?

问题描述

我正在尝试使用 Webpack 4 Split Chunks Plugin 创建多个供应商捆绑包。在这种情况下,我想为 react/react-dom 创建一个块,为 react-router/react-router-dom 创建一个块。

cacheGroups仅包含reactandvendor时,构建按预期工作。捆绑输出是:

- index
- react
- runtime
- vendors

同样,如果我只有 cacheGroupsrouter并且vendor它按预期工作。输出是:

- index
- router
- runtime
- vendors

在任何一种情况下,当创建块时,检查都会显示正确的代码reactrouter在它们各自的情况下。

但是......当我同时包含两者时它不起作用 - 在这种情况下,只有router块被创建,并且react代码被推送到索引(src)包中。

我怀疑正则表达式模式中有问题导致先前的缓存组失效?任何帮助表示赞赏。

这是我的 splitChunks 的 webpack 配置:

splitChunks: {
  cacheGroups: {
    react: {
      test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
      name: 'react',
      chunks: 'all'
    },
    router: {
      test: /[\\/]node_modules[\\/](react-router|react-router-dom)[\\/]/,
      name: 'router',
      chunks: 'all'
    },
    vendor: {
      test(mod) {
        // exclude anything outside node modules
        if (!mod.context.includes('node_modules')) {
          return false;
        }

        // exclude react and react-dom
        if (/[\\/]node_modules[\\/](react|react-dom)[\\/]/.test(mod.context)) {
          return false;
        }

        // exclude react-router and react-router-dom
        if (/[\\/]node_modules[\\/](react-router|react-router-dom)[\\/]/.test(mod.context)) {
          return false;
        }

        // return all other node modules
        return true;
      },
      name: 'vendors',
      chunks: 'all'
    }
  }
}

标签: javascriptregexwebpackwebpack-splitchunks

解决方案


尝试对您的配置进行此操作:

optimization: {
    splitChunks: {
      maxInitialRequests: 4, // This one!

默认值为maxInitialRequests4,因此如果您有超过 4 个捆绑包,它会以某种方式合并其中的一些。


推荐阅读