Sub topic 15
Import Attributes and JSON Modules
This chapter assumes you know how import() returns a promise for a module namespace object, how default exports appear on that object, and how to handle a rejected import with try/catch. Here you will add one more piece: the optional second argument to import(), which carries import attributes.
Why the Runtime Needs a Hint
A module specifier such as ./settings.json does not tell the runtime what kind of file it points to. Browsers ignore file extensions and go by the Content-Type header the server sends. Suppose the runtime simply trusted that header. A compromised or misconfigured server could then send JavaScript where you expected plain data, and that JavaScript would run with your page's privileges.
Import attributes fix this. You state the type you expect, and the runtime checks it. If the response is not JSON, the import fails instead of running unexpected code.
Static and Dynamic Syntax
The static form puts the attributes after a with keyword:
import settings from './settings.json' with { type: 'json' };
console.log(settings.theme);The dynamic form takes an options object as the second argument, and the attributes go under its with key:
const { default: settings } = await import('./settings.json', {
with: { type: 'json' },
});
console.log(settings.theme);The parsed JSON value becomes the module's default export. JSON modules have no named exports, so const { theme } = await import(...) gives you undefined. Destructure default first, then read properties from it.
Common Errors
| Situation | Result |
|---|---|
| Importing `.json` with no attribute | Rejects with a `TypeError` (for example "needs an import attribute of type json") |
| Server sends JSON with a non-JSON `Content-Type` | Rejects in browsers |
| File contains invalid JSON | Rejects with a `SyntaxError` |
| Unknown attribute key such as `{ kind: 'json' }` | Rejects; runtimes refuse attributes they do not support |
| Using the old `assert` keyword | Fails in current Node.js and Chrome, which replaced `assert` with `with` |
The Value Is Shared
JSON modules are cached the same way JavaScript modules are. Every importer of ./settings.json gets the same object, so a change made in one place shows up in all the others:
// a.js
import settings from './settings.json' with { type: 'json' };
settings.theme = 'dark'; // visible to every other importerIf you need a private copy to modify, clone it with structuredClone(settings).
Combining with Error Handling
Because a rejected JSON import works like any other rejected import(), you can reuse the fallback pattern from earlier chapters:
async function loadConfig(env) {
try {
const mod = await import(`./config.${env}.json`, { with: { type: 'json' } });
return mod.default;
} catch (err) {
console.warn(`No config for "${env}", using defaults`, err);
return { theme: 'light' };
}
}
const config = await loadConfig('staging');
console.log(config.theme);Exercise
You write const { version } = await import('./package.json', { with: { type: 'json' } }); and version is undefined, although package.json has a version field. Why, and how do you fix it?
Show answer
A JSON module exposes the parsed value only as its default export and has no named exports. Destructure the default first: const { default: pkg } = await import('./package.json', { with: { type: 'json' } }); console.log(pkg.version);
Exercise
A teammate removes the with: { type: 'json' } option because "the file ends in .json anyway." What happens, and why does the runtime behave that way?
Show answer
The import rejects with a TypeError. The runtime does not go by file extensions. It requires the attribute so it can confirm the content is JSON before using it, which stops a server from slipping in executable JavaScript.