Search code examples
webpackwebpack-4webpack-splitchunks

HOWTO control webpack4 bundle chunks


What seems simple is not clicking for me... I'm trying to create three separate bundles:

(1) node-vendors-[hash].bundle.js: bundle of stuff from node_modules (2) vendor-config-[hash].bundle.js: bundle of all scripts provided by vendors we use our site with config stuff... think multiple services like Google Analytics; each vendor we use on our site provides a snippet with account details (3) our custom script

No matter the config, I keep getting a bundle for each source file in the #2 category above.

const coreVendorSetupFiles = {
  vendor1: './scripts/vendors/vendor1/index.js',
  vendor2: './scripts/vendors/vendor2/index.js',
  vendor3: './scripts/vendors/vendor3/index.js',
  vendor4: './scripts/vendors/vendor4/index.js',
  ourCode: './scripts/ours/index.ts
};

module.exports = {
  entry: coreVendorSetupFiles,
  module: {
    rules: [
      { test: /\.ts$/, use: 'ts-loader' }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendorConfig: {
          test: /[\\/]vendors[\\/]/,
          name: 'vendor-config'
        }
      }
    }
  },
  output: {
    path: path.resolve(__dirname, './../dist'),
    filename: '[name].bundle-[hash].js'
  }
};

What I get every time are 6 bundles... a single one for #1 & #3 above, but 4 additional ones for each script referenced in the "vendors" folder. I know my optimization section is incorrect, but no matter what I change I can't get this working. After search and trying tons of examples, posting in desperation :/


Solution

  • You can't setup chunks through entry points. Entry points used to avoid duplicated load. There it seems you have only one entry point: ./scripts/ours/index.ts

    To split vendors.js use cacheGroups, here you will have such many chunks as npm pakets you have.

     cacheGroups: {
       vendor: {
         test: /[\\/]node_modules[\\/]/,
         vendorname(v) {
           var name = v.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
           return `npm.${name.replace('@', '_')}`;
         },
       },