How webpack 4 code splitting work? Is there a hidd

2019-08-02 07:34发布

问题:

I am trying to understand how Webpack 4 code splitting works under the hood. Is there a hidden code which makes a http request for next chunk?

Follow up question: If I split code between login.js(login page) and app.js(actual app), is it possible to intercept the call from login.js for next chunk and based on successful authentication or not, serve app.js if successful or serve error.js on failed authentication?

回答1:

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. It is usually based on routes.

For better code splitting, Structure your component like that, if authentication gets failed you should route to next route so it will not be imported dynamically.

I hope this would be helpful.



回答2:

I am trying to understand how Webpack 4 code splitting works under the hood. Is there a hidden code which makes a http request for next chunk?

Yeah, there's webpack logic that handles that for us. You just don't need to care about it.

If I split code between login.js(login page) and app.js(actual app), is it possible to intercept the call from login.js for next chunk and based on successful authentication or not, serve app.js if successful or serve error.js on failed authentication?

Depending on how you do, that is totally possible. Code splitting is done via dynamic import, which in other words works the same, but flags that import for webpack saying that it should be downloaded later.

Dynamic import requires @babel/plugin-syntax-dynamic-import. To flag that for webpack, you import('path.to.file') you content. That generates a promise which you need to resolve and do whatever you need with it.