Sub topic 2
Loading JSON on Demand with Dynamic import()
This chapter assumes you know static import/export, async/await, and the with { type: "json" } clause from the previous chapter.
Loading JSON on Demand with Dynamic import()
A static import loads its JSON before any of your code runs. When the file you need depends on runtime data, such as the user's language, use dynamic import() instead. Its second argument is an options object, and the attributes go under the with key:
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);import() resolves to a module namespace object, not to the parsed data. The data is on .default.
One Instance per Module Graph: Caching and Mutation
The runtime fetches, parses, and evaluates a JSON module once. After that, every importer gets the same object. That object is not frozen, so a change made in one module is visible in all the others:
// a.js
import config from "./config.json" with { type: "json" };
config.version = 4;
// b.js (evaluated after a.js)
import config from "./config.json" with { type: "json" };
console.log(config.version); // 4Repeated dynamic imports of the same URL also return this cached instance. If you need a private copy, clone it with structuredClone(config). If you need data that is fresh from disk, read the file directly instead of importing it.
Re-exporting JSON Data from Other Modules
A JSON module has only a default export. A plain JavaScript module can re-export that default under a name, and the re-export carries its own attributes:
// settings.js
export { default as config } from "./config.json" with { type: "json" };
// main.js
import { config } from "./settings.js";
console.log(config.version);When Imports Fail: Common Errors and Their Causes
| Symptom | Cause |
|---|---|
| TypeError saying the module needs a `type: "json"` attribute | The `with` clause is missing |
| Browser refuses to load the module because of its MIME type | The server did not send `Content-Type: application/json` |
| SyntaxError when the module is evaluated | The file is not valid JSON, for example because of trailing commas or comments |
| SyntaxError at link time | A named import such as `import { appName }` |
| Error about an unsupported attribute | An attribute key or value the host does not recognize |
A static import that fails stops the whole module graph from running. A dynamic import that fails rejects its promise, so you can catch the error:
try {
const { default: data } = await import("./maybe.json", { with: { type: "json" } });
console.log(data);
} catch (err) {
console.error("Could not load JSON:", err.name, err.message);
}Exercise
Module a.js runs const m = await import("./c.json", { with: { type: "json" } }); m.default.count = 1;. Later, b.js runs import c from "./c.json" with { type: "json" }; console.log(c.count);. What is printed, and why?
Show answer
It prints 1. Both imports resolve to the same cached JSON module instance, and its default export is a shared, mutable object.