How does the bundling happens when you use something like this:const module = import(`folder1/${someExpression}`);
I mean, I do understand when you pass a plain string to it, but how does webpack understands all the possible outcomes?
Is this a good pattern?
Does it bundle all the files from that folder?
If so, it bundles them all together and does it recursively?
Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.
To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);
Webpack is a command line tool to create bundles of assets (code and files). Webpack doesn't run on the server or the browser. Webpack takes all your javascript files and any other assets and transforms then into one huge file. This big file can then be sent by the server to a client's browser.
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
So, I bumped into this question that gave me an idea on how it works and what to search for. I am posting here so it can help someone else.
The key here is to use Magic Comments. From the the docs:
Inline comments to make features work. By adding comments to the import, we can do things such as name our chunk or select different modes.
webpackMode
It will tell how webapack should bundle your assets. You mark your imports as such:
import(/* webpackMode: "lazy" */`./locales/${language}.json`)
./locales/${language}.json
), where multiple module paths that can potentially be requested.You can also make use of combinations with other magic comments, such as:
/* webpackMode: "lazy-once", webpackChunkName: "all-i18n-data", webpackPrefetch: true */
,
/* webpackMode: "lazy", webpackChunkName: "[request]", webpackPreload: true */
,
I hope it helps! For something a little more in depth:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With