Eric Guan
Eric Guan

Reputation: 15992

Webpack 4: Load splitChunks module through JS during runtime

My webpack build outputs 3 bundles.

  1. The entry point.
  2. node_modules code, generated by splitChunks
  3. The extracted css file.

This is a library meant to be used by other devs, so I don't control the HTML that the entry point is loaded from. A user is going to include the entry point with <script>, then my application code should somehow load bundles 2 && 3, which have hashed names.

To be clear, I don't want to load modules with dynamic imports, (i.e. modules you npm install, or files you import), I want to load the webpack output chunk that contains modules.

(I actually have 2 entrypoints, which is why bundle #2 exists, but I left it out for simplicity.)

Upvotes: 2

Views: 1933

Answers (1)

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8122

Webpack v4 has latest upgrades. Previously if we do code splitting, You can see in devTools of browser, the initiator of main.bundle.js in *(index)* which means index.html requested the main.bundle.js. Afterwards all scripts are loaded from bootstrap_a877…. (a script) This is the Webpack script that is responsible for asynchronously loading files. This script is added to the build automatically when you use Webpack’s dynamic import function.

But in webpack v4 we have runtimeChunk which is actually becomes the initiator of all bundles. You can see it in your dev tools. You need to enable runtimeChunk

optimization: {
    runtimeChunk: 'single',
}

I hope this would be helpful.

My answer on a different post regarding code splitting

Upvotes: 3

Related Questions