Dynamic import(): load modules on demand (ES2020)
What you’ll learn
Section titled “What you’ll learn”- What
import(specifier)returns and how to read default and named exports from it. - How the module cache works: each module is evaluated once, whoever imports it.
- How relative specifiers are resolved, and why wrapping
import()in a helper can break them. - How to load JSON with import attributes (ES2025), handle failures and keep specifiers safe.
Summary
Section titled “Summary”TL;DR: import(specifier) is a function-like expression that loads an ES module at runtime and returns a promise for its module namespace object: default holds the default export, and every named export is a property. It works in modules, classic scripts and CommonJS, inside conditions and functions, with a specifier computed at runtime.
It was added in ECMAScript 2020; the optional second argument for import attributes arrived in ECMAScript 2025. Support is universal in current browsers and runtimes (see Compatibility).
The problem it solves
Section titled “The problem it solves”A static import declaration must sit at the top level of a module and name a fixed string. Everything it names is fetched, linked and evaluated before your code runs, whether or not the user ever needs it. That makes it impossible to:
- load a heavy feature (a PDF exporter, a chart library, an editor) only when the user opens it;
- choose a module at runtime, such as a locale file or a plugin;
- load ES modules from a classic script or CommonJS code.
Before ES2020 the answers were loader libraries, bundler-specific APIs or injected <script> tags. import() standardizes on-demand loading, and bundlers treat each call as a code-splitting point.
Running the samples: save the files in one folder with the paths shown, save each runnable sample as a .mjs file and run it with Node.js 22 (node main.mjs). The outputs shown were produced with Node.js 22.23.
console.log(' [csv.mjs evaluated]');export const extension = 'csv';export default function toCsv(orders) { return ['id,total', ...orders.map((o) => `${o.id},${o.total}`)].join('\n');}console.log(' [json.mjs evaluated]');export const extension = 'json';export default (orders) => JSON.stringify(orders);// main.mjs - OrdersPortal: load an exporter only when the user asks for that format.const exporters = { csv: () => import('./exporters/csv.mjs'), json: () => import('./exporters/json.mjs'),};
async function exportOrders(orders, format) { const load = exporters[format]; if (!load) throw new RangeError(`unsupported format: ${format}`); const { default: serialize, extension } = await load(); return { filename: `orders.${extension}`, body: serialize(orders) };}
const orders = [{ id: 'o-1', total: 40 }, { id: 'o-2', total: 15.5 }];console.log('app started; no exporter loaded yet');console.log(await exportOrders(orders, 'csv'));console.log(await exportOrders(orders, 'csv')); // cached: not evaluated again
const a = await import('./exporters/csv.mjs');const b = await import('./exporters/csv.mjs');console.log('same namespace object:', a === b, '| tag:', a[Symbol.toStringTag]);Output:
app started; no exporter loaded yet [csv.mjs evaluated]{ filename: 'orders.csv', body: 'id,total\no-1,40\no-2,15.5' }{ filename: 'orders.csv', body: 'id,total\no-1,40\no-2,15.5' }same namespace object: true | tag: ModuleThe JSON exporter is never loaded, and the CSV module runs once even though it is imported three times.
How it works
Section titled “How it works”// Fragment: syntaxconst ns = await import(specifier);const ns = await import(specifier, { with: { type: 'json' } }); // ES2025 import attributesconst { default: fn, named } = await import(specifier);- It is syntax, not a function.
importcannot be aliased, passed around or called with.call;const f = import;is aSyntaxError. The parentheses are part of the grammar. - The specifier is any expression. It is evaluated and converted to a string at runtime, so
import(42)looks for a module named"42". - Resolution uses the module or script that contains the
import()call as the base, then follows host rules: URLs in browsers, file paths, package names andexportsmaps in Node.js. - The result is a promise. It fulfills with the module namespace object after the module and its dependencies are loaded and evaluated, including any top-level
awaitin them. The namespace is a sealed, read-only view of live bindings. - Caching: the host’s module map stores each module by resolved URL (and attributes). Later imports, static or dynamic, get the same namespace object without re-running the module.
- Failures reject the promise: a missing file, a network error, a syntax error in the module, or an exception thrown while it evaluates. A
TypeErroris also returned as a rejection, not thrown, when the options argument is malformed or an attribute is unsupported.
Import attributes
Section titled “Import attributes”ES2025 added a second argument whose with property carries import attributes. The standardized one is type: 'json', which loads a JSON file as a module with the parsed data as its default export. Hosts reject attributes they do not support.
// errors.mjs (needs config.json containing {"pageSize":20} next to it)try { await import('./exporters/pdf.mjs');} catch (error) { console.log(error.code, '-', error.constructor.name);}const p = import(42); // the specifier is converted to a string: "42"p.catch((e) => console.log('import(42):', e.code));await p.catch(() => {});try { await import('./exporters/csv.mjs', { with: { type: 'css' } });} catch (e) { console.log(e.constructor.name, e.code); }const config = await import('./config.json', { with: { type: 'json' } });console.log(config.default);Output:
ERR_MODULE_NOT_FOUND - Errorimport(42): ERR_MODULE_NOT_FOUNDTypeError ERR_IMPORT_ATTRIBUTE_UNSUPPORTED{ pageSize: 20 }The error.code values are Node.js-specific; browsers reject with a TypeError for fetch failures. The older assert { type: 'json' } syntax was an earlier draft of this feature that shipped in Chrome and Edge 91 to 125 and Node.js 16.14 to 21; use with.
Resolution belongs to the calling file
Section titled “Resolution belongs to the calling file”export const load = (path) => import(path); // resolves relative to lib/, not the callerimport { load } from './lib/loader.mjs';try { await load('./exporters/csv.mjs'); } catch (e) { console.log('helper failed:', e.code); }const mod = await load(new URL('./exporters/csv.mjs', import.meta.url).href);console.log('with an absolute URL:', mod.extension);Output:
helper failed: ERR_MODULE_NOT_FOUND [csv.mjs evaluated]with an absolute URL: csvResolve paths with new URL(path, import.meta.url) or import.meta.resolve() in the caller before handing them to shared helpers.
Realistic example
Section titled “Realistic example”OrdersPortal loads UI messages for the user’s language. The loader maps input onto an allow-list (never import a raw user-supplied path), memoizes the promise so concurrent callers share one load, falls back to English when a bundle is missing, and removes failed entries so a later call can retry.
// locale.mjs (with locales/en.mjs and locales/de.mjs; fr.mjs is missing on purpose)const SUPPORTED = new Set(['en', 'de', 'fr']); // fr.mjs has not shipped yetconst cache = new Map();
function loadMessages(lang) { const code = SUPPORTED.has(lang) ? lang : 'en'; // allow-list: never import raw user input if (!cache.has(code)) { const promise = import(`./locales/${code}.mjs`) .then((module) => module.default) .catch((error) => { cache.delete(code); // let a later call retry if (code === 'en') throw error; console.warn(`messages for "${code}" unavailable (${error.code}); using en`); return loadMessages('en'); }); cache.set(code, promise); } return cache.get(code);}
const [de, again, fr, xx] = await Promise.all([ loadMessages('de'), loadMessages('de'), loadMessages('fr'), loadMessages('../../etc/passwd'),]);console.log(de.greeting, '|', de === again);console.log(fr.greeting);console.log(xx.greeting);with locales/en.mjs exporting { greeting: "Your orders", ... } and locales/de.mjs exporting { greeting: "Ihre Bestellungen", ... } as default.
Output:
messages for "fr" unavailable (ERR_MODULE_NOT_FOUND); using enIhre Bestellungen | trueYour ordersYour ordersThe template literal keeps a fixed prefix and suffix (./locales/ and .mjs). Bundlers such as webpack and Vite can only split code they can see, and a partly static pattern like this lets them find and package every matching file; a fully dynamic import(userPath) usually cannot be bundled at all.
Common mistakes
Section titled “Common mistakes”- Importing user-controlled specifiers.
import(req.query.plugin)lets a caller load any module the runtime can reach. Map input onto an allow-list or a lookup table of loader functions. - Forgetting
.default.const toCsv = await import('./csv.mjs')gives the namespace, not the function. Destructure{ default: toCsv }. - Assuming a failed load can be retried. Browsers used to keep a failed fetch in the module map, so a retry after a network blip failed again. Chrome and Edge 156 and Firefox 155 retry after HTTP errors; Safari does so only in preview builds. Offer a page reload as the fallback.
- Wrapping
import()in a shared helper with relative paths. The helper’s location becomes the base. Pass absolute URLs. - Lazy-loading what the first render needs. That only adds a request waterfall; import it statically or use
<link rel="modulepreload">. - Expecting a fresh module on each import. Modules are singletons per resolved URL. State inside them is shared; export a factory if callers need separate instances.
- Using
assertinstead ofwithfor JSON.assertwas removed from current engines.
When to use it and when not to
Section titled “When to use it and when not to”| Situation | Use |
|---|---|
| Dependency needed on every run | Static import declaration |
| Heavy feature used by some users or later in a session | import() behind the user action |
| Module chosen at runtime from a known set | import() with an allow-list |
| Loading ES modules from CommonJS or a classic script | import() |
| Startup config that the module cannot work without | Static import, or top-level await import() |
| Deferring evaluation but not fetching | import defer (Stage 3 proposal, not yet standard) |
Two related TC39 proposals are at Stage 3 as of November 2026 and not yet part of the language: deferred module evaluation (import defer) and source phase imports (import source, used for WebAssembly modules). Treat them as experimental.
Compatibility
Section titled “Compatibility”According to MDN’s compatibility data, import() is supported in Chrome 63, Edge 79, Firefox 67, Safari 11.1 (iOS 11.3), Node.js 13.2.0 (and 12.17.0), Deno 1.0 and Bun 1.0; Internet Explorer never supported it. Inside workers it needs Chrome 80, Firefox 114 or Safari 15. Import attributes with with (ES2025) and JSON modules are supported in Chrome 123, Edge 123, Firefox 138, Safari 17.2, Node.js 20.10.0 (and 18.20.0) and Deno 1.37. In TypeScript, import() is kept as written when module is es2020 or later, node16/nodenext or preserve; with commonjs output it is rewritten to a require() call wrapped in a promise.
Interview questions
Section titled “Interview questions”1. What does import() return, and how do you get a default export from it?
A promise for the module namespace object. The default export is the default property, so const { default: fn } = await import('./mod.mjs'). Named exports are properties with their export names.
2. If two parts of an app import() the same module, does it run twice?
No. The module map is keyed by resolved URL (and attributes), so the module is evaluated once and both callers get the same namespace object. To get separate state, export a factory function.
3. Why do bundlers care how you write the specifier?
They split code at import() calls by analyzing the source at build time. A string literal maps to one chunk; a template literal with a static prefix and extension lets them include every matching file. A fully dynamic expression gives them nothing to analyze, so the module may be missing from the build.
4. Is import() a function?
No, it is a syntactic form. You cannot alias it, spread arguments into it or call it through .call. Its base URL comes from the file where it is written, which is why helper wrappers break relative paths.
5. Senior scenario: OrdersPortal’s initial bundle is 2 MB and the reporting and admin screens account for 60% of it. How would you introduce code splitting safely?
Measure first with a bundle analyzer. Put each heavy route’s root component behind import() in the router so it becomes its own chunk, and prefetch likely next routes when the browser is idle. Add a loading state and an error boundary, because chunk loads fail on flaky networks and after a deploy removes old chunk files; keep previous assets available for a while or reload on a version mismatch. Finally, check that nothing on the first screen statically imports a lazy module, or the split does nothing.
Key takeaways
Section titled “Key takeaways”import()(ES2020) loads a module at runtime and returns a promise for its namespace object.- Modules are cached per resolved URL and evaluated once.
- Relative specifiers resolve against the file containing the call.
- Use
{ with: { type: 'json' } }(ES2025) for JSON modules;assertis obsolete. - Allow-list dynamic specifiers, handle rejections, and keep specifiers analyzable for bundlers.
Related pages
Section titled “Related pages”- Modules (import/export): static imports and exports.
- Top-level await: awaiting
import()at module top level. - Async/Await and Promises: consuming the returned promise.
- Hashbang comments: another module-file feature, for runnable CLI scripts.
- Async and modules hub
Official references
Section titled “Official references”- ECMAScript Language Specification: Import Calls (current draft)
- ECMAScript 2020 Language Specification (ECMA-262, 11th edition)
- TC39 proposal: import() and Import attributes (ES2025)
- TC39 proposals: Deferring module evaluation and Source phase imports (Stage 3)
- MDN: import()
- MDN: Import attributes
- Node.js 22: ECMAScript modules