Sub topic 6
Loading JSON on Demand with Dynamic import()
A static import declaration loads its JSON before any of your code runs. Sometimes the module to load is only known at runtime: a locale picked by the user, a feature flag file, or a dataset that is too large to fetch on every page load. Dynamic import() covers these cases, and it accepts import attributes through a second argument.
This chapter assumes you know ES module import and export, Promises and async/await, and the with { type: "json" } clause from the earlier chapters. You also need a runtime that supports import attributes: a current browser, or Node.js 22 or later.
The Shape of a Dynamic JSON Import
import() looks like a function call, but it is special syntax. It takes a module specifier and an optional options object. It returns a Promise that resolves to the module's namespace object.
const module = await import("./config.json", {
with: { type: "json" }
});
console.log(module.default.appName); // "Inventory"Here is how the pieces line up with the static form:
| Static declaration | Dynamic `import()` |
|---|---|
| `import config from "./config.json" with { type: "json" };` | `const { default: config } = await import("./config.json", { with: { type: "json" } });` |
| The specifier must be a string literal | The specifier can be any expression that produces a string |
| The attributes follow the `with` keyword | The attributes sit under the `with` key of the options object |
| Runs before the module body is evaluated | Runs when the expression is reached |
| Failures stop the whole module graph from loading | Failures reject the returned Promise |
The options object has an extra layer of nesting. The attributes do not go directly into the second argument. They go under a property named with, which leaves room for other options in later versions of the language.
// Wrong: the attributes are not wrapped in `with`, so none are sent
// await import("./config.json", { type: "json" });
// Right
await import("./config.json", { with: { type: "json" } });Reading the Namespace Object
The Promise resolves to a module namespace object, the same kind of object you get from import * as ns from "...". A JSON module has exactly one export, default, so the parsed data is always at module.default.
Destructuring with a rename is the usual way to get it out in one line:
const { default: config } = await import("./config.json", {
with: { type: "json" }
});
console.log(config.features); // ["search", "export"]Leaving out .default is a common mistake. module.appName is undefined, because the namespace has no appName property, and no error is thrown. The namespace object is also sealed, so you cannot add properties to it. The data object inside default is a different matter, as the chapter on caching explains.
How the Call Is Processed
The engine checks a few things before it asks the host to load anything. If any check fails, the Promise rejects:
- If the second argument is given but is not an object (or
undefined), the Promise rejects with aTypeError. - If
withis present but is not an object, the Promise rejects with aTypeError. - If any attribute value is not a string, for example
{ type: 1 }, the Promise rejects with aTypeError. - If an attribute key is not supported by the host, the Promise rejects. It is usually a
SyntaxError.
All of these are rejections, not exceptions thrown at the call site. Even a malformed options object gives you a Promise, so try/catch around an await handles every case.
Building Specifiers at Runtime
Dynamic import exists so the specifier can be computed. A loader for translation files is the standard example. Given this layout:
{
"greeting": "Hello",
"farewell": "Goodbye"
}saved as locales/en.json, and a similar locales/fr.json with "Bonjour" and "Au revoir", this module loads one on demand:
// i18n.mjs
const SUPPORTED = new Set(["en", "fr"]);
export async function loadLocale(lang) {
if (!SUPPORTED.has(lang)) {
throw new RangeError(`Unsupported locale: ${lang}`);
}
const { default: messages } = await import(`./locales/${lang}.json`, {
with: { type: "json" }
});
return messages;
}// main.mjs
import { loadLocale } from "./i18n.mjs";
const lang = process.argv[2] ?? "en";
const messages = await loadLocale(lang);
console.log(messages.greeting);Run it with node main.mjs fr and it prints Bonjour.
The allowlist is important. A specifier built from user input can point anywhere the host allows: ../secrets in Node.js, or another path on your origin in a browser. The type: "json" attribute stops a crafted path from running code, because the host will refuse anything that is not JSON. It does not stop the code from reading a JSON file you never meant to expose. Check input against a fixed set before it goes into a specifier.
Fallbacks and Parallel Loads
Because failures arrive as rejections, a fallback is an ordinary try/catch:
async function loadWithFallback(lang) {
try {
return (await import(`./locales/${lang}.json`, {
with: { type: "json" }
})).default;
} catch (error) {
console.warn(`Falling back to English: ${error.message}`);
return (await import("./locales/en.json", {
with: { type: "json" }
})).default;
}
}The catch here catches every kind of failure: a missing file, invalid JSON, or a server that sent the wrong content type. The chapter on errors covers how to tell them apart. If you only want to fall back on "file not found", inspect the error before you swallow it.
To load several files, start every import before awaiting any of them. Promise.all runs the loads at the same time and rejects as soon as one fails:
const json = { with: { type: "json" } };
const [config, en] = await Promise.all([
import("./config.json", json),
import("./locales/en.json", json)
]).then((modules) => modules.map((m) => m.default));
console.log(config.appName, en.greeting);Reusing one options object is fine. The engine reads it when the call is made and does not keep a reference to it.
Use Promise.allSettled instead when a single missing file should not discard the others.
Repeated Calls Return the Same Module
Calling import() twice with the same resolved URL and the same type does not fetch or parse the file twice. The host finds the module in its module map and resolves with the same namespace object, so module.default is the identical object each time:
const a = await import("./config.json", { with: { type: "json" } });
const b = await import("./config.json", { with: { type: "json" } });
console.log(a === b); // true
console.log(a.default === b.default); // trueThis also applies across static and dynamic imports. A file loaded by a static declaration elsewhere in the graph is already cached when your dynamic call runs. So dynamic import does not give you a way to reload a changed file. The caching chapter covers what that sharing means for mutation, and the alternatives chapter shows how to get fresh data.
Where import() Works and Where It Is Analyzed
import() is allowed in ES modules and also in classic scripts, CommonJS files in Node.js, and inline event handlers. That makes it the only way to load a JSON module from CommonJS without require:
// legacy.cjs
async function main() {
const { default: config } = await import("./config.json", {
with: { type: "json" }
});
console.log(config.version);
}
main();Top-level await only works in modules, which is why this example wraps the call in a function.
Bundlers follow a different rule. They can only bundle what they can find when they build. A string literal specifier is fully visible to them. A template literal such as ` ./locales/${lang}.json is usually turned into a set of files that match the pattern, here every .json file in locales/, each emitted as its own chunk. An arbitrary variable such as import(path, ...)` usually cannot be resolved at all and is left for the runtime, which may fail after bundling. Keep the directory part of dynamic specifiers fixed so the tools can see it.
Exercise
This code logs undefined instead of "Inventory" and throws no error. What two things are wrong with it? const m = await import("./config.json", { type: "json" }); console.log(m.appName);
Show answer
First, the attributes must sit under a with key: { with: { type: "json" } }. As written, no type attribute is sent. In a runtime that requires the type, the import would reject instead of logging anything. Second, the data lives on the namespace's default property, so the line should read m.default.appName. Reading m.appName from a namespace that has no such export gives undefined with no error.
Exercise
A function calls import(\./data/${name}.json\, { with: { type: "json" } }) where name comes from a URL query parameter. The type attribute guarantees that only JSON can be loaded. Is that enough to make the function safe? What would you add?
Show answer
No. The attribute stops non-JSON content from being executed, but name could contain ../ segments that reach other JSON files the caller should not read. Check name against an allowlist (or a strict pattern such as /^[a-z]{2}$/) before building the specifier, and reject everything else.
Exercise
You call import("./config.json", { with: { type: "json" } }) three times in a loop, and a static import config from "./config.json" with { type: "json" } exists in another module of the same app. How many times is the file fetched and parsed, and are the resulting default values the same object?
Show answer
The file is fetched and parsed once. All four imports resolve to the same entry in the module map, keyed by the resolved URL and the type. Every default is the identical object, so === comparisons between them are true.