javascriptwebpackmodulebundlewebpack-splitchunks

Webpack 4 and splitChunks - move all vendor code to a separate chunk except for the dynamically imported module


I have a project that looks like this:

module1 is imported dynamically in app.js via import(/* webpackChunkName: 'module1' */ '@path').

I'm trying to configure the splitChunks plugin so it would output:

  1. app chunk including src code without dependencies and packages;
  2. module1 chunk that includes both the source code AND required dependencies from node_modules for the dynamically imported module;
  3. vendor chunk that includes the rest of the dependencies from node_modules;

What is the best way to do that? The application has a single entry, which is app.js


Solution

  • Solved it with the following config. The key here is chunks: inital in vendor cachegroup.

      optimization: {
        splitChunks: {
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 0,
          cacheGroups: {
            vendors: false,
            default: false,
            vendor: {
              chunks: 'initial',
              test: /[\\/]node_modules[\\/]/,
              name: 'vendor',
              reuseExistingChunk: true
            },
          },
        },