Learn JavaScript
❯ errors_modules.dynamic_import

Dynamic import() in JavaScript

$concept

import() loads modules on demand, returning a promise of the namespace — route-based code splitting (load the admin panel only when visited), conditional loading (heavy library only when needed), and computed specifiers (locale files by variable) that static imports cannot express.

Top-level static imports hoist and preload; dynamic imports defer to execution time with full error handling (try/catch around await import). Bundlers split at every import() automatically — architecture expressed as syntax.

$how it works
1

Load on demand

const m = await import("./heavy.js") — module fetches and evaluates exactly when reached.

2

Computed specifiers

await import(`./locales/${lang}.js`) — variable paths impossible statically, routine dynamically.

3

Handle failures

Network/module errors reject — try/catch fallbacks keep features optional, never fatal.

4

Bundlers split here

Every import() becomes a separate chunk loaded on demand — route splitting without configuration.

$example
async function loadMath(op) {
if (op === "fancy") {
let m = await import("./fancy-math.js");
return m.compute(2);
}
return 4;
}
Output
(loads fancy-math.js only when asked; returns 4 otherwise)
1The default path returns immediately — no module fetched, no cost paid.
2The fancy path awaits the dynamic import, then uses its exports normally.
3Loading follows need — startup stays lean, features arrive lazily.
$use cases
Route-based splitting in SPAs (admin, settings on demand)
Conditional heavy libraries (charts, editors, PDFs)
Locale and theme modules loaded by variable
Optional features degrading gracefully on load failure

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.