Madushan PereraMadushan Perera

Published on August 1, 2021

What is Dynamic Module Import ?

Import modules dynamically to your JavaScript code and see the performance difference.

What is Dynamic Module Import ?

Why we need ‘import’ in JavaScript?

The static import is very useful when we want to use read only live bindings which are exporting by other modules in your program. In this way the idea is to manage our code by separating them as we want. This can be functionality, features or component wise. But the entire code is working as a one code block after connecting them by importing.

Below code block shows how we can import modules in a static way.

js

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";

In this way it’s easier to understand the code to some and very helpful for debugging. The import statement cannot be used in the embedded scripts unless the script has a type=’ module.’ Also, we can import modules as a dynamic import.

What’s dynamic import in JavaScript?

Most of the time developers are used to use the standard static import. This will always import the modules at the loading time. No matter what if we use that imported module or not JavaScript always loads the static modules in loading time.

What if we want to import modules conditionally or on demand? This is the place where you need to implement dynamic import in JavaScript.

To use dynamic import call the ‘import()’ as a function as pass the module path as an argument. Then you can use JavaScript promise or await to get the rest of the work done.

js

import("/modules/my-module.js").then((module) => {
// Do something with the module.
console.log("module-->", module);
});

js

let module = await import("/modules/my-module.js");

When to use dynamic import?

  • When importing statically significantly slows the loading of your code.
  • When importing statically significantly increases your program's memory usage.
  • When the module you are importing does not exist at load time
  • When the module being imported has side effects, and you do not want those side effects unless some condition is true.
  • When the import specifier string needs to be constructed dynamically.

Thank you for reading and Happy Coding 🥳