'How do I make the npm dependencies in my "main" webpack bundle available to others without duplication in webpack 5?

My application always has a "main" webpack bundle, and sometimes has additional webpack bundles which are needed on some but not on most pages.

To save loading time, I want to prevent these "extra" bundles from containing duplicate copies of any npm module that is also imported by the "main" bundle. I am not concerned about dependencies shared only between the "extra" bundles.

In essence what I want is very similar to this (drawing from the webpack documentation on code splitting):

  entry: {
    main: {
      import: './src/main.js',
      dependOn: 'shared'
    },
    extra1: {
      import: './src/extra1.js',
      dependOn: 'shared'
    },
    extra2: {
      import: './src/extra2.js',
      dependOn: 'shared'
    },
    shared: [ 'lodash', 'popper', 'vue', 'et cetera' ]
  }

However I would like shared to be automatically rather than manually populated with all of the npm dependencies of main, and shipped as part of main (a single HTTP request), but still available without duplication to the extra1 and extra2 bundles. I want to achieve this without changes to the source code.

I do not want npm dependencies used only by extra1 and/or extra2 to be shared, not even if they happen to appear in both, because I know this scenario will be rare in my application and avoiding extra load time for those who only need main is paramount. The only dependencies I want to share with the other bundles are those used at least once in main.

I have been reading over the SplitChunksPlugin documentation but after doing so I am still not sure it supports my use case.

I understand that I could use aggressive chunk splitting here to move every npm dependency to its own chunk, however I cannot guarantee that HTTP2 will be used in the production environments, so I believe that wouldn't be the right choice in my case.

I am using webpack 5.

Thank you for your help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source