Dynamic imports in JavaScript
Dynamic imports in JavaScript

Dynamic imports in JavaScript

Summary
Lazy load JavaScript using dynamic imports
Tags
JavaScript
Created at
Jun 11, 2023
Author
Kshitij Jain
The default import syntax, import x from 'y' has few caveats:
  • You can’t call it conditionally at runtime (e.g. inside if statements).
  • You can’t load the module at runtime on demand (can’t lazy load).
  • The import path must be a string, it can't be a variable.
 
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'); }
 
💡
Did you know: You can use React.lazy with dynamic imports to lazy load components when they are rendered for the first time.