Skip to content

Dynamic Imports in Javascript

Published:

The default import syntax, import x from 'y' has few caveats:

Dynamic import solves these issues.

Syntax:

import(modulePath);

It returns a promise which resolves into an object containing all the exports of that module.

For e.g.

Suppose you have a module named custom:

// custom.js
export const a = 1;
export const b = 2;

const c = 3;
export default c;

You can dynamically import this module like below:

import('./custom').then((module) => {
  const a = module.a;
  const b = module.b;
  const c = module.default;
});

// or by using async, await
async function foo() {
  const { a, b, default: c } = await import('custom');
}

You can use React.lazy with dynamic imports to lazy load components when they are rendered for the first time.