Sub topic 5
JSON Modules Have Only a Default Export
This chapter assumes you already know ES module import and export syntax, have seen the with { type: "json" } clause from the previous chapter, and can run module code in Node.js (version 22 or later) or a modern browser. Every example imports this config.json file:
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}What a JSON Module Exports
A JSON module is a module with exactly one export, named default. The value of that export is whatever JSON.parse would return for the file's text. There are no other exports. Top-level keys do not become named exports, even when the top-level value is an object.
import config from "./config.json" with { type: "json" };
console.log(config.appName); // "Inventory"
console.log(config.features[0]); // "search"The identifier config is your local name for the default export, and you can choose any name you like. Inside the engine, the module record for config.json lists one export entry. A JavaScript module, by comparison, lists one entry for every export statement in its source.
Why Named Imports Fail
Developers often try this, especially if they have used a bundler that allowed it:
import { appName } from "./config.json" with { type: "json" };Under the standard, this code never runs. The failure happens at link time, which is the phase after the engine has fetched and parsed every module in the graph and before any of them executes. During linking, the engine matches each import name to an export in the target module. config.json exports only default, so the name appName has no match, and linking throws a SyntaxError. Exact wording depends on the engine:
| Runtime | Typical message |
|---|---|
| Node.js / Chrome (V8) | `SyntaxError: The requested module './config.json' does not provide an export named 'appName'` |
| Firefox | `SyntaxError: import not found: appName` |
| Safari | `SyntaxError: Importing binding name 'appName' is not found.` |
Because linking happens before any module evaluates, a single bad named import stops the whole module graph. Code in unrelated modules does not run either, including code that would have run before the faulty import in a script. A try...catch around the import cannot catch it, because a static import declaration is not a statement that executes.
The design reasons
The proposal authors chose a default export only, on purpose. Their reasons explain several edge cases you will run into.
- JSON keys are not always identifiers. A key such as
"app-name","2024", or""is valid JSON but cannot be a JavaScript binding name. Mapping some keys to exports and silently dropping others would be confusing. - The top-level value is not always an object. A JSON file can contain an array, a string, a number,
true,false, ornull. With named exports, those files would have no sensible exports. A default export handles every case the same way. - Named exports would imply live bindings. An ES module export is a live binding, but a JSON value is plain data. Treating properties as bindings would raise hard questions. For example, what should happen to the export
versionif someone runsconfig.version = 4? One default export holding an ordinary object avoids the question. - The behavior matches across environments. Browsers, Node.js, and Deno all follow the same rule, so the same import works everywhere without depending on a bundler.
Here is a JSON file whose top-level value is an array. It imports exactly like the object case:
["red", "green", "blue"]import colors from "./colors.json" with { type: "json" };
console.log(colors.length); // 3Forms That Work
You can reach the default export in three ways. They all return the same object.
import config from "./config.json" with { type: "json" };
import * as ns from "./config.json" with { type: "json" };
import { default as cfg } from "./config.json" with { type: "json" };
console.log(Object.keys(ns)); // [ 'default' ]
console.log(ns.default === config); // true
console.log(cfg === config); // true
console.log(Object.prototype.toString.call(ns)); // "[object Module]"Listing the keys of the namespace object makes the export shape visible: there is only default. People sometimes reach for the namespace form hoping that ns.appName will work. It returns undefined, because the namespace object only has properties for exports.
Repeating the import with the same specifier and attributes does not load the file again. All three local names point at one cached object. A later chapter, "One Instance per Module Graph", covers what that sharing means once you mutate the object.
The Idiomatic Pattern: Import, Then Destructure
To work with individual fields under their own names, import the default export and destructure it in a normal statement:
import config from "./config.json" with { type: "json" };
const { appName, version } = config;
console.log(appName, version); // Inventory 3Destructuring is ordinary runtime code, so you get its full feature set. That includes defaults for missing keys, renaming of keys that are awkward identifiers, and nested patterns:
import config from "./config.json" with { type: "json" };
const {
appName: name,
timeoutMs = 5000,
features: [primaryFeature, ...otherFeatures]
} = config;
console.log(name); // "Inventory"
console.log(timeoutMs); // 5000 (not in the file, default applied)
console.log(primaryFeature); // "search"
console.log(otherFeatures); // [ 'export' ]For keys that are not valid identifiers, use a quoted key in the pattern, as in const { "app-name": appName } = data;.
Destructuring copies, it does not bind
A named import is a live binding. A destructured variable is not. const { version } = config copies the current value of config.version into a new local constant. If any code later changes config.version, your version constant keeps the old value. Nested objects and arrays are copied by reference, so otherFeatures above is a new array, while a destructured features would be the same array that every importer shares.
Gotcha: Migrating From Bundler-Era Code
Older webpack setups, and some versions of other bundlers, let you write import { appName } from "./config.json" without attributes. The bundler compiled it into a property access, and tree shaking could drop unused keys. When you move that code to native JSON modules, or to a bundler in a strict standards mode, every such import breaks at link time.
A safe migration has three steps:
- Search for imports from
.jsonfiles that use braces:import {....json. - Replace each one with a default import plus the
with { type: "json" }clause. - Add a destructuring line, or change uses to
config.key.
// Before (bundler-only, non-standard):
// import { appName, version } from "./config.json";
// After (standard):
import config from "./config.json" with { type: "json" };
const { appName, version } = config;The rewrite costs you key-level tree shaking. The whole parsed file becomes part of the module graph. For large JSON files that only a few code paths need, load the file conditionally with dynamic import() (next chapter), or read it at runtime with fetch or the file system (covered in "Choosing Between JSON Modules, fetch, and File Reads").
Summary of Behaviors
| Import form | Result |
|---|---|
| `import config from "./config.json" with { type: "json" }` | Works; `config` is the parsed value |
| `import * as ns from ... with { type: "json" }` | Works; data is at `ns.default` |
| `import { default as cfg } from ... with { type: "json" }` | Works; same as a default import |
| `import { appName } from ... with { type: "json" }` | `SyntaxError` at link time; nothing in the graph runs |
| `ns.appName` after a namespace import | `undefined`; only `default` exists |
Exercise
A teammate writes import { version } from "./config.json" with { type: "json" }; at the top of main.js, and main.js also imports logger.js, which prints a startup message. When they run the program, no startup message appears. Explain why, and rewrite the import so it works.
Show answer
The named import fails while the module graph links. config.json exports only default, so the engine throws a SyntaxError before any module evaluates, and logger.js never runs. Fix: import config from "./config.json" with { type: "json" }; followed by const { version } = config;.
Exercise
Given import * as ns from "./colors.json" with { type: "json" };, where colors.json contains ["red", "green", "blue"], what do Object.keys(ns), ns.length, and ns.default[1] evaluate to?
Show answer
Object.keys(ns) is ["default"]. ns.length is undefined, because the namespace object has only a default property. ns.default[1] is "green".
Exercise
Module A runs import config from "./config.json" with { type: "json" }; const { version } = config; config.version = 10; console.log(version, config.version);. What does it print, and why?
Show answer
It prints 3 10. Destructuring copied the primitive value 3 into a local constant when the line ran. The later assignment changes the shared object, not the copy.