Sub topic 3
Import Attributes: The with { type: "json" } Clause
This chapter assumes you already know how ES modules use import and export, and that you can run a module in a browser or in Node.js. The previous chapter explained what a JSON module is. This one covers the syntax that asks for one: the import attributes clause. You will see where the clause can appear, which rules the parser applies to it, and how a runtime uses the attributes when it loads a module.
The Shape of the Clause
An import attribute is a key/value pair added to a module request. You write it after the module specifier, using the with keyword followed by an object-like list:
import config from "./config.json" with { type: "json" };
console.log(config.appName);This uses the sample file from earlier in the tutorial:
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}The clause has three parts:
- The
withkeyword. It is a reserved word reused for this purpose. It has no connection to the oldwithstatement, which modules don't allow anyway because they always run in strict mode. - A list in braces of
key: valueentries separated by commas. - The entries themselves. Today the only key that browsers and Node.js understand is
type.
The braces look like an object literal, but they are not one. The parser reads them with a separate, much stricter grammar, described below.
Where the Clause Can Appear
Import attributes belong to the module request, not to the bindings you import. Any syntax that causes a module to be loaded can carry them.
| Form | Example | Covered in detail |
|---|---|---|
| Default import | `import config from "./config.json" with { type: "json" };` | This chapter |
| Namespace import | `import * as ns from "./config.json" with { type: "json" };` | Default export chapter |
| Side-effect import | `import "./config.json" with { type: "json" };` | This chapter |
| Re-export | `export { default as config } from "./config.json" with { type: "json" };` | Re-exporting chapter |
| Dynamic import | `import("./config.json", { with: { type: "json" } })` | Dynamic import chapter |
A side-effect import loads, parses and caches the JSON without binding anything. That sounds pointless, but it lets you preload or validate a file. If the JSON is malformed, the whole module graph fails to load before any of your code runs:
// preload.js
import "./config.json" with { type: "json" };
console.log("config.json is valid JSON");A namespace import works too. The namespace object has a single property, default:
import * as ns from "./config.json" with { type: "json" };
console.log(Object.keys(ns)); // [ 'default' ]
console.log(ns.default.version); // 3The clause cannot go anywhere else. You can't attach it to a local export (one with no from), because that doesn't load a module.
Grammar Rules the Parser Enforces
The braces accept far less than an object literal does. The rules are checked when the module is parsed, so breaking one is a SyntaxError that stops the whole graph from loading.
Values must be string literals
Each value must be a literal string written in the source. Variables, template literals, numbers and booleans are rejected:
// All of these are SyntaxErrors:
// const t = "json";
// import a from "./config.json" with { type: t };
// import b from "./config.json" with { type: `json` };
// import c from "./config.json" with { type: true };
import config from "./config.json" with { type: "json" };This is intentional. Static imports are resolved before any code runs, so the loader must be able to read every attribute straight from the source text. If you need to choose an attribute at runtime, use dynamic import(), which accepts an ordinary object.
Keys are identifiers or strings
A key can be a bare identifier name or a string literal. These two lines mean the same thing:
import a from "./config.json" with { type: "json" };
import b from "./config.json" with { "type": "json" };
console.log(a === b); // true: same module request, same instanceComputed keys ([name]: "json"), shorthand ({ type }) and spread ({ ...opts }) are not allowed.
No duplicate keys
Repeating a key is an early error, even when both values agree:
// SyntaxError: duplicate key
// import config from "./config.json" with { type: "json", type: "json" };Empty lists and trailing commas
with {} is valid and means "no attributes". A trailing comma after the last entry is also valid. You rarely need either by hand, but code generators produce them, so it helps to know they are legal:
import config from "./config.json" with { type: "json", };
console.log(config.features.length); // 2How the Runtime Uses Attributes
Parsing produces a module request for each import. A module request is a record that holds the specifier string and its list of attributes. The JavaScript engine passes that record to the host, meaning the browser or Node.js. The host decides what to do with it.
The host does several things with the attributes.
- It rejects keys it doesn't recognize. The specification requires a host to throw a
SyntaxErrorwhen it gets an attribute key it doesn't support, rather than quietly ignoring it. Without that rule, a typo such astpye: "json"would load the file as JavaScript. - It uses
typeto choose a module kind. Withtype: "json"the host parses the response as JSON and builds a synthetic module whose default export is the parsed value. With notype, the host treats the resource as JavaScript. - It checks the resource against the declared type. A browser compares the type with the response's MIME type, and Node.js uses the file extension and its loader rules. Later chapters cover the exact errors and the security reasons behind this check.
- It includes the type in the cache key. A module is cached by its resolved URL together with its type. Every
type: "json"request for the same URL returns the same module instance, as the earlier example witha === bshowed.
Attributes Describe the Module, Not How You Import It
The specification has one rule that explains the design. Attributes must not change how the specifier resolves, and for the same URL and attributes the host must return the same module every time. A module's identity depends only on what it is.
Some practical consequences follow:
- You cannot use attributes to request two different parsings of one JSON file under the same type.
- Every importer of a JSON file must write the same
type: "json"attribute. Omitting it in one file doesn't give that file "the raw text". The file is loaded as JavaScript and fails. - New attribute keys proposed in the future must follow the same rule. That keeps the module graph predictable.
Formatting and Readability
Formatters usually keep the clause on the same line as the specifier. When an import is long, break it inside the braces of the bindings rather than splitting the attributes off:
import {
default as config
} from "./config.json" with { type: "json" };
console.log(config.appName);You will still see older code that uses assert instead of with. That is the earlier import assertions syntax, which current runtimes reject, and it has its own migration chapter. If you see assert, the code predates the version of the feature described here.
Common Mistakes at the Syntax Level
| Mistake | What happens | Fix |
|---|---|---|
| Omitting the clause on a `.json` import | The host loads it as JavaScript and it fails | Add `with { type: "json" }` |
| Using a variable as the value | `SyntaxError` at parse time | Use a string literal, or dynamic `import()` |
| Misspelling the key (`tpye`) | `SyntaxError`: unsupported attribute | Correct the key |
| Repeating `type` | `SyntaxError`: duplicate key | Keep one entry |
| Putting attributes inside the binding braces | `SyntaxError` | Place `with { ... }` after the specifier |
| Passing `{ type: "json" }` directly to `import()` | Ignored or rejected, since the options object needs a `with` key | Use `{ with: { type: "json" } }` |
Exercise
Which of these lines are valid, and why? (1) import c from "./c.json" with { "type": "json", }; (2) const k = "json"; import c from "./c.json" with { type: k }; (3) import "./c.json" with { type: "json" }; (4) import c from "./c.json" with { type: "json", mode: "strict" };
Show answer
(1) is valid: a key may be a string literal and a trailing comma is allowed. (2) is a SyntaxError because attribute values must be string literals in the source. (3) is valid: a side-effect import loads and validates the JSON without binding anything. (4) parses, but current hosts reject it with a SyntaxError because mode is not a supported attribute key.
Exercise
Module a.js has import x from "./data.json" with { type: "json" }; and module b.js has import y from "./data.json" with { "type": "json" };. Both are in the same module graph. Are x and y the same object? Explain using the cache key.
Show answer
Yes. Quoting the key doesn't change the attribute. Both requests resolve to the same URL with type "json", so the host returns the same cached module instance, and both default exports point to the same parsed object.
Exercise
Why does the specification require hosts to reject unknown attribute keys instead of ignoring them?
Show answer
If unknown keys were ignored, a misspelled key such as tpye: "json" would silently drop the type, and the file would be loaded as JavaScript. Rejecting unknown keys turns that mistake into a SyntaxError at load time. It also lets future keys be added without old hosts misinterpreting them.