Rahul Singh
Rahul Singh

Reputation: 19622

How to bundle each node_module as separate bundle in webpack?

I have a React project where we are using many dependencies. I was following this hackernoon post in which the author mentions how to split each node_module as a separate file as npm-package1.js, ...2.js, etc.

How do I achieve it in my webpack configuration? My current webpack config which I have been trying to tinker with:

const prodWebpackConfig = {
  entry: {  },
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'initial'
        }
      }
    }
  }
};

I am running this file which always generates app, runtime, styles and vendor.js in my dist. I am not able to see all the NPM packages as bundles. How do I achieve this configuration?

Upvotes: 3

Views: 3576

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121975

It looks like the intended links to the author's Gists aren't working correctly, but you can still see them on GitHub. The webpack.config.js for those examples looks like:


module.exports = {   entry: {
    main: path.resolve(__dirname, 'src/index.js'),
    ProductList: path.resolve(__dirname, 'src/ProductList/ProductList.js'),
    ProductPage: path.resolve(__dirname, 'src/ProductPage/ProductPage.js'),
    Icon: path.resolve(__dirname, 'src/Icon/Icon.js'),   },   output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',   },   plugins: [
    new webpack.HashedModuleIdsPlugin(), // so that file hashes don't change unexpectedly   ],   optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            // get the name. E.g. node_modules/packageName/not/this/part.js
            // or node_modules/packageName
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

            // npm package names are URL-safe, but some servers don't like @ symbols
            return `npm.${packageName.replace('@', '')}`;
          },
        },
      },
    },   
  }, 
};

Source: https://gist.github.com/davidgilbertson/c9af3e583f95de03439adced007b47f1

Upvotes: 7

Related Questions