【问题标题】:Exclude certain module from a chunk webpack 4从块 webpack 4 中排除某些模块
【发布时间】:2018-11-28 23:06:27
【问题描述】:

如何使用 webpack 4 指定我不想要一个模块,假设我不想要供应商文件中的 lodash(不管后果),我该怎么办?

这是实际配置:

splitChunks: {
  name: 'vendors',
  maxAsyncRequests: 1,
  maxInitialRequests: 2,
  chunks: 'initial',
}

【问题讨论】:

    标签: javascript reactjs webpack webpack-4


    【解决方案1】:

    test 也可以采用方法。这允许很大的灵活性。比如……

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

    【讨论】:

    • 对于特定的 pckgs,如 react 将“\\node_modules\\react\\”之类的字符串放入数组中以进行排除。
    • 这为我指明了正确的方向,但是我有一些模块的上下文为undefined,因此我在解决方案中的代码周围添加了一个条件if (module.context) {...},并且在该条件之外我添加了return false 语句,以便不包含那些没有上下文的模块
    【解决方案2】:

    您可以使用负前瞻来做到这一点:

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

    【讨论】:

      【解决方案3】:

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

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

      因此,对于您的用例,您可以修改 RegExp 以排除您想要的任何模块。当然,缺点是您必须与正则表达式纠缠不清,并且该特定测试条件的确切格式超出了我的专业知识。我知道optimization.splitChunks 上的文档仍然很少,所以我希望这至少可以帮助您指明正确的方向。

      【讨论】:

      • 正是他所问的,而你说的超出了我的专业范围
      【解决方案4】:

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

      webpack.config.js

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

      此示例基于SplitChunksPlugin example from the Webpack docs

      【讨论】:

        【解决方案5】:

        稍作修改的答案@ndequeker

        test: /[\\/]node_modules[\\/](?!lodash)(.[a-zA-Z0-9.\-_]+)[\\/]/
        

        它对我有用

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-02-28
          • 1970-01-01
          • 1970-01-01
          • 2017-12-23
          • 2019-10-26
          • 1970-01-01
          • 2013-03-11
          相关资源
          最近更新 更多