Sub topic 1
How ES Modules Load: A Quick Recap
Prerequisites
This chapter assumes you already know:
- ES module
importandexportsyntax - JSON syntax and
JSON.parse - How to run JavaScript in a browser or Node.js
The Loading Pipeline
An ES module goes through three phases before any of its code runs:
- Construction: the host fetches each file, parses it, and finds its
importstatements, then repeats for every dependency. - Linking: the host connects each import to the matching export. A missing export causes an error here, before any code runs.
- Evaluation: each module's top-level code runs once, and the result is cached in the module map.
What a JSON Module Is
A JSON module is a .json file loaded through the module system. The host parses the file as JSON. It does not run the file as code. The parsed value becomes the module's export.
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}The with { type: "json" } Clause
Import attributes add metadata to an import. You write them after the module specifier:
import config from "./config.json" with { type: "json" };
console.log(config.appName); // "Inventory"
console.log(config.features[0]); // "search"The type: "json" attribute tells the host which kind of module you expect.
Why the Type Attribute Is Required
Browsers decide how to treat a fetched file from its MIME type, not from its file extension. Suppose config.json comes from a third-party server. If that server is compromised and returns text/javascript, a loader without the attribute would run that response as code inside your page. JSON never runs, so you expected inert data and got code execution.
With type: "json", the host checks that the response really is JSON. If it is not, the import fails. Leaving the attribute out on a JSON file also fails.
Only a Default Export
A JSON module exposes the whole parsed value as its default export and has no named exports. Named imports therefore fail during linking:
// Fails: a JSON module has no named exports
// import { appName } from "./config.json" with { type: "json" };
import config from "./config.json" with { type: "json" };
const { appName, version } = config;
console.log(appName, version);Exercise
A server returns data.json with the MIME type text/javascript, and your code imports it using with { type: "json" }. What happens, and why is that the safe outcome?
Show answer
The import fails because the MIME type does not match the JSON type you asserted. This is safe because the response is never executed as JavaScript, so a compromised server cannot run code through a file you expected to be data.
Exercise
Why does import { version } from "./config.json" with { type: "json" }; throw before any code runs?
Show answer
A JSON module has only a default export. The linking phase cannot find a version export, so it throws before evaluation starts.