In a web build, how does importing a JSON file differ from the browser's native JSON module, and when should large JSON be fetched instead?
answer
- the type attribute
- one default export natively
- compiled into the chunk
- named keys are a convenience
- big data, own request
basics
~20 sNatively, with { type: 'json' } is required and the module has one default export. A bundler compiles the JSON into the importing chunk, often allowing named imports; large or changing data is better emitted as a file and fetched.
solid answer
~50 sIn a browser, `import gazetteer from './gazetteer.json' with { type: 'json' }` fetches the file as its own request, checks that it is served as JSON, and gives you a single default export; named imports are not allowed, and omitting the attribute fails. A bundler instead turns the file into a JavaScript module inside the importing chunk, often as an object literal or, for large files, a `JSON.parse` of a string, because engines parse JSON faster. Many bundlers also accept the import without the attribute and allow named imports of top-level keys, which lets some of them drop keys nobody uses, but that code no longer runs natively. The cost is that the data is downloaded and parsed with the chunk and is re-sent whenever the chunk changes, so a large gazetteer is better emitted as a file and fetched when needed.
code
javascript · 11 lines// standard and portable: one default export, attribute required natively
import gazetteer from './gazetteer.json' with { type: 'json' }
const { sites } = gazetteer
// bundler-only convenience: a named import of a top-level key
// (a native JSON module rejects this)
import { regions } from './regions.json'
// large or frequently updated data: emitted as a file, fetched on demand
const mapUrl = new URL('./gazetteer-full.json', import.meta.url)
const fullGazetteer = await (await fetch(mapUrl)).json()go deeper
Recall the standard form, a default import with with { type: 'json' }, and that a bundler compiles the data into the chunk that imports it.
Explain how native JSON modules and bundled JSON imports differ in attributes, exports and delivery, and why bundler-only forms hurt portability.
Decide between importing and fetching by size, update cadence and who needs the data, and recognise cache coupling when data shares a file with code.
Set the rule for shared packages to use the standard form, and for where large datasets live, so data changes never force code to be re-downloaded.
## The standard form JavaScript modules can import JSON directly, using **import attributes**: ```js import gazetteer from './gazetteer.json' with { type: 'json' } ``` The rules for a **native JSON module** are strict and easy to forget: - The `type: 'json'` attribute is **required** in browsers; without it, the browser expects JavaScript and fails on a JSON response. - The response must be served with a JSON media type. The attribute is a safety check: a file that unexpectedly arrives as JavaScript is refused instead of executed. - The module has **one default export**, the parsed value. Named imports such as `import { sites } from './gazetteer.json'` are not allowed. - It is fetched as **its own request**, like any other module. The same attribute works with dynamic import, as the `with` property of the second argument. ## What a bundler does with it A bundler treats the JSON file as another node in the module graph and turns it into a JavaScript module **inside the chunk** that imports it. Common behaviours, which vary by tool: - the data is emitted as an object literal, or, for large files, as `JSON.parse('...')` on a string, since engines parse a JSON string faster than an equivalent object literal; - the import is accepted with or without the attribute; - **named imports of top-level keys** are often allowed as a convenience, and a build that sees only `sites` imported may be able to leave other top-level keys out of the output, while a default import of the whole object generally keeps everything. | | Native JSON module | Bundled JSON import | |---|---|---| | `with { type: 'json' }` | Required | Usually optional | | Exports | One default export | Default, often plus named top-level keys | | Delivery | Separate request, media-type check | Compiled into the importing chunk | | Unused keys | All parsed | Some builds can drop unused top-level keys | | Runs without a build | Yes | Only if written in the standard form | ## The portability trap Code that relies on bundler conveniences, a missing attribute or a named import, works only while that build is in the chain. The same module fails when loaded unbundled, by a test runner that follows native rules, or by a different tool. Writing the standard form, a default import with the attribute, keeps the module portable; destructure the object after importing if you only need part of it. ## When to fetch instead of import Compiling data into a chunk has real costs: 1. **Download and parse with the code.** The museum's 1.5 MB gazetteer of collection sites would be downloaded and parsed before the chunk that imports it can run. 2. **Cache coupling.** Data and code share one file, so a typo fix in the gazetteer re-sends the code, and a code change re-sends the gazetteer. 3. **No lazy access.** When the import sits in a chunk every visitor loads, everyone pays for the whole file, even those who never open the map. For large or frequently updated data, emit the file as an asset and fetch it at runtime: ```js const url = new URL('./gazetteer.json', import.meta.url) const gazetteer = await (await fetch(url)).json() ``` The build emits the file, the browser caches it independently, and only the code that needs it pays for the request. Loading the data through a dynamic import, so it lands in its own chunk, is a middle ground; how chunks are split is its own subject. ## A rule of thumb - **Small configuration-like JSON**, such as a few kilobytes of labels, read on startup: import it. - **Large datasets, or data that changes on a different schedule from the code**: emit it and fetch it when needed. - **Shared libraries**: use the standard form, so the import works with and without a build. ## Related file types WebAssembly follows a similar split: a build can expose a `.wasm` file as a URL to fetch, or, where it supports the WebAssembly ES-module integration proposal, as a module whose exports are the instance's exports. Instantiating it is the WebAssembly interop subject.
- Why would a bundler emit a large JSON file as `JSON.parse` of a string instead of an object literal?A JavaScript engine parses a JSON string faster than an equivalent object literal, because JSON's grammar is much simpler than JavaScript's. For large data that difference is measurable at startup, so some bundlers switch to the string form above a size threshold.
- Why does a module with a named JSON import fail in a test runner that loads modules natively?Named imports from JSON are a bundler convenience; the standard JSON module has only a default export, and natively the `type: 'json'` attribute is also required. A runner that follows native rules rejects the import, so the portable form is a default import with the attribute, destructured afterwards.
- A browser can import a `.json` file without the type attribute.
- Native JSON modules support named imports of top-level keys.
- Importing JSON is free at runtime because it is only data.
- Bundled JSON is fetched as a separate file, like an emitted image.
- Editing imported JSON invalidates only the JSON file in the cache.