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';
>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).