Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude certain module from a chunk webpack 4

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',
}
like image 533
Miguel Avatar asked Jun 19 '18 22:06

Miguel


People also ask

What is split chunk?

splitChunks.If the current chunk contains modules already split out from the main bundle, it will be reused instead of a new one being generated. This can affect the resulting file name of the chunk. webpack.config.js module.

Can webpack split code into separate files?

Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel.

How are webpack chunks loaded?

Webpack injects some code into main. js which takes care of lazy loading async chunks and stops from loading same chunks again and again. When a route changes, React router calls a Webpack function to load a chunk file and Webpack after done loading runs it, which chunk then would internally ask React to do something.


3 Answers

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
 },
like image 166
geedew Avatar answered Oct 06 '22 11:10

geedew


You can do it using the negative lookahead:

test: /[\\/]node_modules[\\/]((?!(lodash)).*)[\\/]/
like image 40
Davide Patti Avatar answered Oct 06 '22 11:10

Davide Patti


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.

like image 1
A. Lamansky Avatar answered Oct 06 '22 12:10

A. Lamansky