Sub topic 3
From assert to with: Migrating Legacy Code and Choosing a Loader
This chapter assumes you know static and dynamic JSON imports from the earlier chapters, and that you can run code in a browser and in Node.js.
Migrating Legacy Import Assertions
Early versions of this feature used the assert keyword. The proposal changed to with, and current runtimes no longer accept assert. For example, Node.js 22 removed it. To migrate, swap the keyword and leave the attribute object as it is:
// Legacy syntax (deprecated, rejected by current runtimes)
// import config from "./config.json" assert { type: "json" };
// Current syntax
import config from "./config.json" with { type: "json" };The same change applies to dynamic imports. Rename { assert: { type: "json" } } to { with: { type: "json" } }.
JSON Modules in the Browser
When a browser loads a module, it checks the response's MIME type, not the file extension. The server must send a JSON type such as application/json. If it sends text/plain or text/html, the import fails. This often happens with an SPA fallback that returns index.html for a missing file.
JSON Modules in Node.js
Node.js requires with { type: "json" } on every JSON import from an ES module. Without it, the import throws ERR_IMPORT_ATTRIBUTE_MISSING. In CommonJS, require("./config.json") still works without any attribute.
Choosing a Loader
| Need | Use |
|---|---|
| Fixed data known at build time | Static JSON import |
| Data that changes at runtime, or a fresh copy on each read | `fs.readFile` with `JSON.parse` |
| Browser data that needs headers, retries, or status checks | `fetch` with `response.json()` |
import { readFile } from "node:fs/promises";
const text = await readFile(new URL("./config.json", import.meta.url), "utf8");
const config = JSON.parse(text);
console.log(config.appName);TypeScript and Bundlers
TypeScript 5.3 and later understand with. To get a typed default import, enable resolveJsonModule and set module to esnext or nodenext. Vite, webpack, Rollup, and esbuild accept the syntax too. They usually inline the JSON into the bundle, so the browser makes no separate request at runtime.
Other Module Types
The type attribute is not limited to JSON. Chromium-based browsers support CSS module scripts:
import sheet from "./styles.css" with { type: "css" };
document.adoptedStyleSheets = [sheet];The default export is a CSSStyleSheet object.
Exercise
An app imports ./config.json with assert { type: "json" }. It runs on Node.js 20 but fails on Node.js 22. In the browser, the same import also fails, because the server returns the file as text/plain. What two fixes are needed?
Show answer
First, change assert to with, because Node.js 22 rejects assert. Second, configure the server to send config.json with a JSON MIME type such as application/json, because browsers check the MIME type before they load the module.