17

How can I specify that I don't want a module in a chunk with webpack 4, let's suppose I don't want lodash in the vendor file (No matter the consequences), what can I do?

This is the actual configuration:

splitChunks: {
  name: 'vendors',
  maxAsyncRequests: 1,
  maxInitialRequests: 2,
  chunks: 'initial',
}
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Miguel
  • 1,577
  • 2
  • 15
  • 29

5 Answers5

16

A test can also take a method. This allows a lot of flexibility. For instance..

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
 },
geedew
  • 1,368
  • 12
  • 16
  • For specific pckgs like react put rather string like "\\node_modules\\react\\" into the array for exclude. – apincik Oct 25 '19 at 06:41
  • This pointed me in the right direction, however I had some modules for which context was `undefined`, so I added a condition `if (module.context) {...}` around the code in your solution, and outside of that condition I added a `return false` statement, in order not to include those modules that have no context – Giorgio Tempesta Sep 24 '20 at 09:29
8

You can do it using the negative lookahead:

test: /[\\/]node_modules[\\/]((?!(lodash)).*)[\\/]/
Davide Patti
  • 3,391
  • 2
  • 18
  • 20
2

You can exclude a specific folder from node_modules by updating the test property. In the example below we create a single chunk containing all vendors, except the Lodash module.

webpack.config.js

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

This example is based on the SplitChunksPlugin example from the Webpack docs.

ndequeker
  • 7,932
  • 7
  • 61
  • 93
1

The config for loading all of a project's dependencies from /node_modules into a chunk called vendors looks like this:

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

So for your use case, you could modify the RegExp to exclude whatever modules you desire. Of course, the downside is that you have to tangle with regular expressions, and the exact formatting of that particular testing condition is beyond my expertise. I know the documentation on optimization.splitChunks is still pretty sparse so I hope this at least helps point you in the right direction.

A. Lamansky
  • 284
  • 2
  • 7
1

slightly modified answer @ndequeker

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

It worked for me