author-pic

JOSEPH CHOW

How to use Dynamic Imports in ES2020

Published: December 28, 2020

One of the most exciting new features, for me, in ES2020 is the ability to dynamically import your files. This means that rather than importing all your potentially necessary files at the top of your file, you can just import files based on need.

Imports

Import was introduced in ES2015, since then we have been able to natively load our modules in our code. We could divide our modules into export classes or functions that organizes our code into manageable sections. However, the JavaScript engine needed to resolve all the imports first before executing the code.

Why use dynamic imports?

As developers, we should always be aiming to reduce load times anywhere possible. It may not be necessary, but optimizing code always feels nice. Using dynamic imports, we can avoid importing a large bundle which will let us have blazing fast apps. Dynamic imports also allows us to navigate situations where a module you want to import does not exist when the component is first loaded. This way, you can set logic to load the files with only a few lines of code.

How do we use them?

Here is an example with the old system introduced with ES2015. Note that without extra bundling tools, we need to set the type attribute specifically to module:

<script type="module">
  import add from './add.js';

  add(7, 4); // returns 11
</script>

ES2020 allows us to use the import keyword as a function. There is now also no need to set the type because import() will work from a script:

<!-- No need to typeset -->
<script>
  import('./add.js')
    .then(module => module.default(3, 7)) //returns 10
    .catch(error => // log error here);
</script>

A really common use case scenario is when you may potentially never need to import a module, like when something is loaded dependent on user action. For example, this allows us to be super flexible loading page modules based on button presses:

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

Now the user experience is improved with snappier loads with only a few simple refactors. If you want to read more about ES2020 and Dynamic Importing, check out the MDN docs.

If you like it, share it!