从Webpack 4的一个块中排除特定模块

17

我如何在 webpack 4 中指定不将某个模块打入chunk?比如我不想让lodash被打入vendor文件(无论后果如何),我该怎么做?

这是当前的配置:

splitChunks: {
  name: 'vendors',
  maxAsyncRequests: 1,
  maxInitialRequests: 2,
  chunks: 'initial',
}
5个回答

16

一个测试也可以使用方法。这样可以提供很大的灵活性。例如...

vendor: {
    test(mod/* , chunk */) {


     // Only node_modules are needed
     if (!mod.context.includes('node_modules')) {
       return false;
     }
     // But not node modules that contain these key words in the path
     if ([ 'lodash', 'react'].some(str => mod.context.includes(str))) {
       return false;
     }
     return true;
   },
   name: 'vendor',
   chunks: 'all',
   reuseExistingChunk: true
 },

对于特定的包,如React,请将类似于“\node_modules\react\"的字符串放入要排除的数组中。 - apincik
这指引我朝着正确的方向前进,但是我有一些模块的上下文是undefined,所以我在你的解决方案中添加了一个条件if (module.context) {...}来包围代码,并在该条件之外添加了一个return false语句,以便不包括那些没有上下文的模块。 - Giorgio Tempesta

8
您可以使用负向先行断言来完成:

test: /[\\/]node_modules[\\/]((?!(lodash)).*)[\\/]/

2
您可以通过更新“test”属性来从“node_modules”中排除特定文件夹。在下面的示例中,我们创建一个包含所有供应商(除了Lodash模块)的单个块。

webpack.config.js

module.exports = {
  //...
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/](!lodash)[\\/]/,
          name: 'vendor',
          chunks: 'all',
        }
      }
    }
  }
};

该示例基于Webpack文档中的SplitChunksPlugin示例

1

/node_modules 加载项目所有依赖项到名为 vendors 的块的配置如下:

optimization: {
    splitChunks: {
        cacheGroups: {
            commons: { test: /[\\/]node_modules[\\/]/, name: "vendors", chunks: "all" }
        }
    }
}

所以对于您的用例,您可以修改RegExp以排除您想要的任何模块。当然,缺点是您必须处理正则表达式,并且特定测试条件的确切格式超出了我的专业知识范围。我知道关于optimization.splitChunks的文档仍然相当稀少,所以我希望这至少能帮助您指明正确的方向。

你需要准确回答他的问题,但你说这超出了我的专业范围。 - 29er

1
略微修改的答案 @ndequeker
test: /[\\/]node_modules[\\/](?!lodash)(.[a-zA-Z0-9.\-_]+)[\\/]/

它对我有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接