Webpack splitChunks how to get a chunk for each npm package (the chunk should include the dependencies for each package)
Asked Answered
A

0

8

I want to split my chunks with Webpack the following way:

Whenever I import an NPM package, like

import styled from "styled-components";

I want a chunk like:

styled-components.[contenthash:5].js  // INCLUDING ITS DEPENDENCIES

Here is the config I'm using:

webpack.config.js

optimization: {
  runtimeChunk: 'single',
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name(module) {
          const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
          return `npm.${packageName.replace('@', '')}`;
        },
      },
    },
  },
}

And right now I'm getting every dependency of styled-components as a different chunk. For example: the 3 packages below are all required by styled-components

enter image description here

Ideally, I would also like to have a commons or shared chunk to avoid possible modules there are required by more than one module.

Does anybody know how to to that?

Antihero answered 17/2, 2020 at 18:46 Comment(1)
I think you can pass a function for chunks for each cacheGroup you have created and then use path prefix to solve the problem.Spritsail

© 2022 - 2024 — McMap. All rights reserved.