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?
CodePudding user response:
Dynamic imports in Webpack are performed by a Babel plugin.
According to the Github issue there are 2 workarounds:
import(/* webpackIgnore: true */"...")
or
eval(`import('${moduleURL}')`).then(...)
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.
CodePudding user response:
Without getting into the reasons of why as was already mentioned in a comment to your question, the simple solution to use native dynamic import()
with webpack is to include a magic comment /* webpackIgnore: true */
to all dynamic import statements:
import(/* webpackIgnore: true */ 'path-to-module.js')
If you would like to do this at build time to all dynamic import statements you can use magic-comments-loader.