Sub topic 6
Loading JSON on Demand with Dynamic import()
This chapter assumes you already know static import ... with { type: "json" } and that a JSON module exposes its parsed value only as the default export. You should also be comfortable with Promises and async/await.
A static import loads its JSON before any of your code runs. That suits configuration you always need. It is a poor fit for data you need only sometimes, such as one locale file out of twenty or a large dataset behind a button. Dynamic import() loads a module at runtime, when your code asks for it.
The Options Argument
import() accepts a second argument, an options object. You pass the import attributes under its with key:
const module = await import("./config.json", {
with: { type: "json" }
});
console.log(module.default.appName); // "Inventory"The call returns a Promise. That Promise resolves to a module namespace object, the same kind of object you get from import * as ns. The parsed JSON is on its default property. Forgetting .default is the most common mistake here. If you do, you end up reading properties of the namespace instead of your data, and they come back undefined.
You can destructure the namespace directly:
const { default: config } = await import("./config.json", {
with: { type: "json" }
});Choosing the File at Runtime
The specifier can be any string expression, so you can build the path from runtime values:
async function loadLocale(lang) {
const module = await import(`./locales/${lang}.json`, {
with: { type: "json" }
});
return module.default;
}
const messages = await loadLocale("en");
console.log(messages.greeting);The type attribute is still required. Without it, the host treats the file as JavaScript and rejects it, just as it would for a static import.
Handling Failure with a Fallback
A static import that fails stops the whole module graph from loading. A dynamic import fails only the Promise it returned, which means you can recover. Missing files, invalid JSON, and wrong content types all show up as a rejection:
async function loadLocaleSafe(lang) {
try {
const module = await import(`./locales/${lang}.json`, {
with: { type: "json" }
});
return module.default;
} catch (error) {
console.warn(`Locale "${lang}" unavailable: ${error.message}`);
const fallback = await import("./locales/en.json", {
with: { type: "json" }
});
return fallback.default;
}
}Caching Still Applies
Dynamic imports use the same module map as static imports. If you call import() again with the same resolved URL and the same type, you get back the module instance that already exists. The loader does not fetch or parse the file a second time. This is a good way to load data lazily, but you can't use it to re-read a file that has changed since it was first loaded.
Common Mistakes
| Symptom | Cause |
|---|---|
| Data properties are `undefined` | You read from the namespace instead of `module.default` |
| Rejection mentioning module type or MIME type | `with: { type: "json" }` is missing |
| Attributes silently ignored or syntax error | You passed `{ type: "json" }` directly instead of nesting it under `with` |
Exercise
What does this code log, and how do you fix it? const data = await import("./config.json", { type: "json" }); console.log(data.appName);
Show answer
The attributes are not nested under with, so the host ignores them. It then tries to load the file as JavaScript and rejects the import. Even with the attributes corrected, data.appName is undefined, because the parsed JSON lives on default. The fix is const data = (await import("./config.json", { with: { type: "json" } })).default;, which logs "Inventory".
Exercise
Two different functions each call import("./locales/fr.json", { with: { type: "json" } }). How many times is the file fetched and parsed?
Show answer
Once. Both calls resolve to the same URL with the same type, so the second call gets the module instance that is already in the module map.