Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Usage of import('something') vs. import from 'something'

I came across the following from MDN:

var promise = import("module-name");

Is this deprecated, or when would that ever be used? I’m only familiar with the syntax of:

import promise from 'module-name';

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following is a static import:

import module from "module-name";

It’s statically resolved, before any code is executed.

This is a dynamic import:

const promise = import("module-name");

The reason why it’s named promise is because import(...) returns a promise that resolves to the imported module (errors if module not found).

So you can use it like this:

import("my-mod").then((myMod) => {
    myMod.func();
});

Or the more preferred async/await syntax:

const myMod = await import("my-mod");

myMod.func();

Dynamic imports are executed and resolved at runtime which is why you must wait for it to complete. They’re commonly used for code-splitting, lazy loading, or importing modules when needed (plugins could be an example).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading