Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: put every external package into its own chunk

I am currently experimenting with code splitting in Webback4.

I'd like to put every external package (from node_modules) into its own chunk. Can someone please provide me a hint how to do it?

This is how far I got so far (except from webpack.config.js)

  optimization: {
    runtimeChunk: {
      name: "runtime"
    },
    splitChunks: {
      chunks: "all",
      name(module) {
        return module.resource && module.resource.replace(/\//g, "_");
      }
    }
  }

But now, every single JS file is a separate chunk. So, I'd like to do it per package.

Ideally, the filename should be of form:

<package-name>-<version>.js

for example:

protobufjs-6.1.3.js

Help?

Bonus: could I also somehow generate content hash for the filename?

like image 817
user3612643 Avatar asked Oct 15 '25 18:10

user3612643


1 Answers

How about this:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: path.resolve(__dirname, 'src/index.js'),
  plugins: [
    new webpack.HashedModuleIdsPlugin(), // so that file hashes don't change unexpectedly
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
  },
  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('@', '')}`;
          },
        },
      },
    },
  },
};

You can further explanation of this in the following article: https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758

like image 78
Dayem Siddiqui Avatar answered Oct 17 '25 13:10

Dayem Siddiqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!