How can I get the vendors chunk names of an async chunk with Webpack?

949 views Asked by At

Let's say I have 3 async chunks that were created by dynamic imports:

const Notes = lazy(() => import(/* webpackChunkName: "notes" */ 'pages/Notes'))
const Lists = lazy(() => import(/* webpackChunkName: "lists" */ 'pages/Lists'))
const Files = lazy(() => import(/* webpackChunkName: "files" */ 'pages/Files'))

Will generate:

notes.g3g43g.js
lists.534535.js
files.234f8t.js

Each of these chunks contains it's own vendor dependencies.

So inside notes.g3g43g.js we have react-big-calendar and lodash.

However, when using SplitChunksPlugin, we can set the chunks option to all:

optimization: {
  runtimeChunk: 'single',
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: ({ context }) => (context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
      }
    }
  }
}

From this point, react-big-calendar and lodash might be split into their own seperate vendor chunks (so they can be used by other async chunks aswell), sometimes the chunk name will be the same as the package name, but other times it can just be the id of the entry point (like 466).

My question is: how can I tell what are the async vendor chunks of notes.g3g43g.js?

I've been looking into the compilation object emitted to HtmlWebpackPlugin but could not find anything that will point me to what notes chunk depends on:

new HtmlPlugin({
  filename: `${name}.html`,
  scriptLoading: 'module',
  templateContent: ({ compilation }) => {
    console.log(compilation)
  }
})

Any ideas how can I find out?

Disclaimer: What I attempt to do is generating multiple html documents (one for each route) and then inlining a preload of all their relevent scripts in the document.

notes.html:

<head>
  <script type="module" src="js/runtime.dc0c50.js"></script>
  <script type="module" src="js/%40emotion.16b5a2.js"></script>
  <script type="module" src="js/react-dom.db73d8.js"></script>
  <script type="module" src="js/main.f337ee.js"></script>
</head>

<body>
  <link rel="preload" href="js/notes.g3g43g.js" as="script">
  <link rel="preload" href="js/react-big-calendar.35994c.js" as="script">
  <link rel="preload" href="js/466.f9ej43.js" as="script">

  <div id="root"></div>
</body>

This will prevent additional roundtrips to the CDN, since every chunk already has all of it's dependencies.

0

There are 0 answers