Separate bundles form dynamically imported node modules

686 Views Asked by At

I have the following configuration in webpack config for split chunks. This perfectly creates two bundles vendors (node modules that were imported in initial files) and common(node modules that were imported in the lazy-loaded components)

splitChunks: {
        name: true,
        cacheGroups: {
          default: false,
          vendors: false,
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: "vendors",
            chunks: "initial"
          },
          common: {
            test: /[\\/]node_modules[\\/]/,
            name: "common",
            minChunks: 2,
            chunks: "async",
            priority: 10,
            reuseExistingChunk: true,
            enforce: true
          }
        }
      },

Question- But there are some node modules that I do not want to be included in any of the bundles. Neither the above two nor the main bundles but to be created separately alone.

import('lodash') should create a lodash.chunk.js.

import('underscore') should create a underscore.chunk.js.

Can I do it thought the magic comments? /* webpackIgnore: true*/

1

There are 1 best solutions below

0
On

Here your lodash will get added to the common chunk based on the current splitchunks configuration. To load it as an separate chunk, change your splitchunks configuration to

var vendorCheck = function vendorCheck(module) {
  var request = module.userRequest;
  // Specify the packages in the condition that need not be present in vendor chunk
  // Here I am excluding the package lodash from vendor chunk
  return request && request.indexOf('node_modules') >= 0 && request.indexOf('node_modules/lodash') === -1
};

var lodashCheck = function lodashCheck(module) {
  var request = module.userRequest;
  return request && request.indexOf('node_modules/lodash') >= 0
}

cacheGroups: {
    default: false,
    'lodash': {
      name: 'lodash',
      chunks: 'all',
      minChunks: 1,
      test: lodashCheck
    },
    vendor: {
      name: 'vendor',
      chunks: 'all',
      minChunks: 1,
      test: vendorCheck
    },
    common: {
        test: vendorCheck,
        name: "common",
        minChunks: 2,
        chunks: "async",
        priority: 10,
        reuseExistingChunk: true,
        enforce: true
    }
}