Skip to content
jshacks.dev
Fundamentals

Dynamic import and Top Level await in JavaScript Modules

The import() function loads a module on demand and returns a promise, and top-level await lets a module wait for async work. See both and their catches.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite, TypeScript and npm logos.

A static import is resolved before any code runs, which is what makes it analyzable, and also what makes it rigid. You cannot import a module only on one branch, you cannot choose the file at runtime and you cannot defer the cost of a heavy dependency until the user needs it. The function form, import(), removes all three limits, and top-level await removes the last awkwardness of modules: the need to wrap startup work in an async function. This post covers both with output from Node.js 24, the caching and error behavior that surprise people, the ordering rules for top-level await, and the situations where each one is the wrong tool. Modules are loaded from data: URLs so that every example is self-contained. The static side is in the post on ES modules, and the JSON form in the post on import attributes.

import() returns a promise for the namespace

The argument is any string, evaluated at runtime. The result resolves to the same namespace object that import * as ns would give.

JavaScript
const toSpecifier = (code) => "data:text/javascript," + encodeURIComponent(code);

const math = await import(toSpecifier("export const double = (n) => n * 2; export default 'math';"));
console.log(Object.keys(math), math.double(21), math.default);

const names = ["alpha", "beta"];
const loaded = await Promise.all(
  names.map((name) => import(toSpecifier(`export const name = ${JSON.stringify(name)};`))),
);
console.log(loaded.map((m) => m.name));

const { readFile } = await import("node:fs/promises");
console.log(typeof readFile);

const viaThen = await import(toSpecifier("export const kind = 'then';")).then((m) => m.kind);
console.log(viaThen);
Text
[ 'default', 'double' ] 42 math
[ 'alpha', 'beta' ]
function
then

The first call produced a namespace with named and default exports. The second loaded two modules chosen from an array, concurrently, which a static import cannot express. The third loaded a Node.js built-in on demand. import() works anywhere, including inside a function, an if branch and a CommonJS file, which is the standard way for CommonJS code to load an ES module.

Loading code only when it is needed

The common reason to use import() is to defer a heavy module until a feature is used. The cost is paid once, at first use, and the cached module is reused afterward.

JavaScript
const log = [];

const heavy = "data:text/javascript," + encodeURIComponent(`
  globalThis.__log.push("heavy module evaluated");
  export function render(items) {
    return items.map((item) => "<li>" + item + "</li>").join("");
  }
`);

globalThis.__log = log;

async function showReport(items) {
  log.push("report requested");
  const { render } = await import(heavy);
  return render(items);
}

log.push("startup done");
console.log(log);

console.log(await showReport(["a", "b"]));
console.log(await showReport(["c"]));
console.log(log);
Text
[ 'startup done' ]
<li>a</li><li>b</li>
<li>c</li>
[
  'startup done',
  'report requested',
  'heavy module evaluated',
  'report requested'
]

Startup finished without evaluating the heavy module. The first report loaded and ran it, and the second reused the cached instance, so "heavy module evaluated" appears once. In a browser this is the basis of code splitting: a bundler turns each import() into a separate file that the page fetches on demand, and a route or a chart library loads only when the user goes there. The trade-off is a delay at first use, which you can hide by starting the import early, on hover or when the browser is idle, and awaiting the promise later.

Errors and optional dependencies

A failed import rejects the promise. In Node.js the error carries a code, which lets you tell "not installed" from "installed and broken".

JavaScript
const attempts = [
  "./does-not-exist.js",
  "no-such-package-installed",
  "data:text/javascript,export default ;",
  "data:text/javascript,throw new Error('init failed')",
];

for (const specifier of attempts) {
  try {
    await import(specifier);
  } catch (error) {
    console.log(error.code ?? "(none)", "|", error.name);
  }
}

async function loadOptional(name, fallback) {
  try {
    return await import(name);
  } catch (error) {
    if (error.code === "ERR_MODULE_NOT_FOUND") return fallback;
    throw error;
  }
}

const result = await loadOptional("not-installed-either", { default: "fallback used" });
console.log(result.default);
Text
ERR_MODULE_NOT_FOUND | Error
ERR_MODULE_NOT_FOUND | Error
(none) | SyntaxError
(none) | Error
fallback used

A missing file and a missing package both give ERR_MODULE_NOT_FOUND. A syntax error in the module is a SyntaxError with no code, and an exception thrown while the module runs is that exception. The helper treats only the first kind as "absent", and rethrows everything else, because swallowing a syntax error in a plugin hides a real bug, a rule explained in the post on error handling. Be aware that a module not found inside an installed package also uses the same code, so a stricter check compares the message with the name you asked for.

Computed specifiers and import.meta.resolve

A dynamic specifier can be built from data, which suits plugin systems and locale files. Resolve relative paths against the module with import.meta.resolve(), or with new URL().

JavaScript
const locales = {
  en: "export const greeting = 'Hello';",
  de: "export const greeting = 'Hallo';",
};

async function loadLocale(code) {
  const source = locales[code] ?? locales.en;
  const { greeting } = await import("data:text/javascript," + encodeURIComponent(source));
  return greeting;
}

console.log(await loadLocale("de"), await loadLocale("fr"));

console.log(import.meta.resolve("./helpers.js").startsWith("file://"));
console.log(import.meta.resolve("node:fs"));
console.log(new URL("./data.json", import.meta.url).pathname.endsWith("/data.json"));
Text
Hallo Hello
true
node:fs
true

The locale code selected a module, with an unknown code falling back to English. Never pass user input straight to import(): a specifier chosen by a user can load arbitrary code, so map input to a fixed set of known files, as the example does with an object. import.meta.resolve() returns the URL a specifier would load without loading it, useful for passing a path to a worker or checking existence.

Top-level await

Inside an ES module, await can be used at the top level, outside any function. The module's evaluation pauses until the promise settles, and modules that import it wait too.

JavaScript
const toSpecifier = (code) => "data:text/javascript," + encodeURIComponent(code);

globalThis.__events = [];

const slowConfig = toSpecifier(`
  globalThis.__events.push("config: start");
  await new Promise((resolve) => setTimeout(resolve, 20));
  export const settings = { retries: 3 };
  globalThis.__events.push("config: ready");
`);

const consumer = toSpecifier(`
  import { settings } from ${JSON.stringify(slowConfig)};
  globalThis.__events.push("consumer sees retries=" + settings.retries);
  export const ready = true;
`);

globalThis.__events.push("before import");
const mod = await import(consumer);
globalThis.__events.push("after import");

console.log(globalThis.__events);
console.log(mod.ready);
Text
[
  'before import',
  'config: start',
  'config: ready',
  'consumer sees retries=3',
  'after import'
]
true

The consumer module did not run until the config module finished its await, so settings was defined when the consumer read it, and the consumer's own code appears after "config: ready". That is the value of top-level await: a module can load a configuration file, open a connection or fetch a value, and export the result as a plain binding, with importers needing no knowledge of the wait. Before it existed, modules exported a promise or an initialization function and every user had to await it.

Siblings run in parallel

Top-level await delays only the modules that depend on the waiting one. Sibling modules that do not import each other still evaluate concurrently, so the total wait is the longest, not the sum.

JavaScript
const toSpecifier = (code) => "data:text/javascript," + encodeURIComponent(code);

globalThis.__order = [];

const make = (name, ms) => toSpecifier(`
  globalThis.__order.push("${name} start");
  await new Promise((resolve) => setTimeout(resolve, ${ms}));
  globalThis.__order.push("${name} end");
  export const name = "${name}";
`);

const [a, b] = [make("a", 30), make("b", 10)];

const parent = toSpecifier(`
  import { name as first } from ${JSON.stringify(a)};
  import { name as second } from ${JSON.stringify(b)};
  export const both = [first, second];
`);

const { both } = await import(parent);
console.log(both);
console.log(globalThis.__order);
Text
[ 'a', 'b' ]
[ 'a start', 'b start', 'b end', 'a end' ]

Both siblings started before either finished, and the shorter wait ended first. The parent ran after both. A sequential wait inside one module, with two await expressions in a row, would take the sum, so independent work belongs in Promise.all. This is the same advice as for any async code, applied to the top level.

The catches

Top-level await is allowed only in modules, not in classic scripts or CommonJS files. A module that never settles blocks everything that imports it, with no error, which looks like a hung process.

JavaScript
const toSpecifier = (code) => "data:text/javascript," + encodeURIComponent(code);

const failing = toSpecifier(`
  await Promise.reject(new Error("startup failed"));
  export const never = 1;
`);

const importer = toSpecifier(`
  import { never } from ${JSON.stringify(failing)};
  export const reached = never;
`);

for (const specifier of [failing, importer]) {
  try {
    await import(specifier);
  } catch (error) {
    console.log(error.message);
  }
}

console.log(await import(failing).then(() => "ok", (e) => "cached failure: " + e.message));
Text
startup failed
startup failed
cached failure: startup failed

A rejection in a top-level await makes the module fail to load, and every importer fails with the same error. The failure is cached, so a second import gets the same rejection and does not retry. Put code that can fail, and that you want to retry, in a function, and keep top-level await for startup work that cannot meaningfully recover. Cycles of modules that wait on each other can deadlock, and require() of a module that uses top-level await throws ERR_REQUIRE_ASYNC_MODULE in Node.js, so a library that wants to support CommonJS consumers should avoid it.

Where each one stops being the right tool

Use a static import for anything always needed, since it lets tools check names and remove dead code. Use import() for code that is optional, large or chosen at runtime. Use top-level await for startup values that every importer needs and cannot work without, such as parsed configuration or a loaded model. Do not use it for work that could be done lazily on first use, because it delays every importer, including tests and tools that load the module for a single export.

The syntax is defined in the specification under import calls and top-level await, and MDN's pages on dynamic import and await cover each.

Also inAsync
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.