🚀 Dynamic Imports (Code Splitting) | ES2020 Feature

Did you know you can import a file dynamically?

What does that mean?

Instead of having all your imports at the top of your file, you can import files as you need them and actually just load the data needed as it’s needed.

We have been doing this for a while with the help of Webpack or other build tools. Having it as a native feature will mean you won’t have to worry about the build tools and you can just focus on creating great applications.

In this video, we will refactor code so you can start using it today.

For more details scroll down. 👇

The static form is preferable for loading initial dependencies and can benefit more readily from static analysis tools and tree shaking.

Why dynamically import?

Static imports will slow down your application, by dynamically importing you can drastically speed up your load times. By not having one single large bundle you can archive crazy fast applications. This is known as "code splitting" as the code is delivered in smaller bundles as required.

Another reason you may want to dynamically import is if the module you are importing does not exist at load time.

How?

To dynamically import a module, the import keyword may be called as a function. When used this way, it returns a promise.

import('/modules/some-module.js')
  .then((module) => {
    // Now you can use the module here.
  });

But for a much cleaner await keyword.

let module = await import('/modules/some-module.js');

There are often times where you may never need to import a module (think of an unvisited page in a single page application). We can dynamically import based on user actions too which make dynamic importing super flexible.

Here's a sample of how you would dynamically load a module when the user clicks an element.

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

So it's that easy! This can drastically improve your user experience if you can build it into your workflow.

If you are looking for more information check out the MDN docs for Dynamic Importing: 🔗 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports

Subscribe on Codú

Es2020JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.