Dynamic Import - patrickcole/learning GitHub Wiki

Dynamic Import

Modules can now be dynamically imported into an application. This means that no longer are module bundles the only way to perform this action of "code splitting".

Traditionally, module bundlers such as Webpack could split the code up into bundles that would be loaded as needed. Now, applications can be configured to import modules as they are needed. For example, if the user clicks a button:

document.getElementById("button")
.addEventListener("click", async () => {
    const { app } = await import("./app.js");
    app();
});

Now the app code is loaded only when the user clicks the button to perform the import process. This means that initial load code can be smaller and pieces of code that are modularized can be imported as needed.

One important piece to note, dynamically imported modules are done via an async promise. The example above utilized async/await to execute the load process.


Sources