Lately I've been deep diving more about JS modules, Webpack, the difference between ES modules and CommonJS, and I came across the dynamic import topic. I was curious on how Webpack converts the dynamic import() statement and when I take a look at the generated bundled JS from webpack, turns out it loads the imported module by adding a <script> tag with src to it, and then removing it after the script has finished loading.
May I know why it is implemented this way? I thought we can use the import() statement right away as long as the entry script tag has the type="module". Why does webpack need to convert it?
Dynamic imports in Webpack are performed by a Babel plugin.
According to the Github issue there are 2 workarounds:
or
Also, if you switch from Webpack to Vite (which uses ESbuild or SWC instead of Babel) - you should be able to utilize the native
import()feature of the major browsers.