It’s All About (The) DYNAMIC MODULE IMPORTS IN JAVASCRIPT

It’s All About (The) DYNAMIC MODULE IMPORTS IN JAVASCRIPT

Dynamic Module Imports in javascript

If you are reading this article then you are most likely aware of static module imports.

import static.png

The above code allows you to split up your JavaScript across multiple files and import them only when needed. The issue, though, is this code is always downloaded immediately by the browser leading to potentially slow page loads. This is where dynamic module imports come in.

How To Use Dynamic Module Import?

Dynamic module imports are very similar to static module imports, but the code is loaded only when it is needed instead of being loaded right away. This means your page load speed will be much quicker and the user will only ever load JavaScript code that they are actually going to use.

Here is a simple example of how to download the above module using dynamic module imports.

import dyanmic.png

As you can see this code is pretty similar to using a normal import but instead, this import is a function that returns a promise. This promise contains all the details of the module.

You will notice, though, that the default export of the module must actually be destructured from the promise return value. This is why we have the code default: User which is mapping the default export to the User variable.

You can also use async/await to clean this up even more.

import using async await.png

This code works the same as the promise-based version, but in my opinion, is a bit cleaner and easier to work with.

Did you find this article valuable?

Support Thyagaraju N by becoming a sponsor. Any amount is appreciated!