Sub topic 14
TypeScript and Bundlers: Types and Build Output
Earlier chapters covered how browsers and Node.js load JSON modules directly. Most real projects add two more steps first: TypeScript checks the code, and a bundler such as Vite, esbuild, webpack, or Rollup rewrites it. Each tool has its own rules for JSON imports. Some of those rules are looser than the runtime's rules, so code can pass type checking and bundle cleanly, then fail when it runs unbundled.
This chapter assumes you know basic tsconfig.json options (module, moduleResolution, outDir) and have used at least one bundler. It uses the same config.json as earlier chapters:
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}How TypeScript Sees a JSON Import
By default, TypeScript refuses to resolve .json files. The resolveJsonModule option turns resolution on. With it enabled, TypeScript reads the JSON file and infers a type from its contents:
import config from "./config.json" with { type: "json" };
// Inferred type:
// { appName: string; version: number; features: string[] }
const name: string = config.appName; // OK
config.version.toFixed(1); // OK, version is number
config.missing; // Error: property 'missing' does not existTypeScript widens the types. "Inventory" becomes string, and 3 becomes number, not the literal types "Inventory" and 3. You cannot attach as const to an import. If you need narrower types or a documented shape, assign the import to an annotated variable. The compiler then checks that the file matches the interface:
import raw from "./config.json" with { type: "json" };
interface Config {
appName: string;
version: number;
features: Array<"search" | "export" | "print">;
}
// Fails to compile if config.json drifts from the interface.
// The features array widens to string[], so it needs an explicit check or cast.
export const config: Config = {
...raw,
features: raw.features as Config["features"],
};Compiler Options That Control JSON Imports
Several options work together, and the right combination depends on what runs the output.
| Option | Role for JSON imports |
|---|---|
| `resolveJsonModule` | Lets TypeScript resolve and type `.json` imports. Required in nearly every setup. |
| `module` | Decides which import-attribute syntax is allowed and whether TypeScript keeps it in the output. The `with` syntax requires `esnext`, `nodenext`, or `preserve`. |
| `moduleResolution` | `nodenext` follows Node's rules. `bundler` follows bundler rules, which are looser. |
| `esModuleInterop` / `allowSyntheticDefaultImports` | Needed for `import config from` when compiling to CommonJS. |
| `outDir` | When set, `tsc` copies imported JSON files into the output folder next to the compiled JavaScript. |
TypeScript has accepted the with syntax since version 5.3. Earlier versions, from 4.5 on, accepted only assert. If your toolchain pins an old TypeScript version, the migration from assert to with described in the previous chapter has to wait until you upgrade it.
Targeting Node.js directly
When tsc output runs in Node.js without a bundler, use the Node module settings:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"resolveJsonModule": true,
"outDir": "dist",
"strict": true
}
}Since TypeScript 5.7, nodenext enforces Node's actual behavior in ES module files. A JSON import must carry with { type: "json" }, and only a default import is allowed. Newer releases also reject the legacy assert keyword under nodenext. This is the strictest mode, and it matches what Node.js does at runtime.
// src/main.ts, compiled with module: nodenext in an ESM package
import config from "./config.json" with { type: "json" }; // OK
// import config from "./config.json"; // Error: needs type "json"
// import { appName } from "./config.json" with { type: "json" }; // Error: no named exports
console.log(config.appName);The emitted dist/main.js keeps the with clause unchanged, and tsc copies config.json into dist/ so the relative path still resolves.
Targeting a bundler
When a bundler consumes the code, the usual settings are:
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"noEmit": true,
"strict": true
}
}In this mode TypeScript is lenient. It allows a JSON import without the attribute, and it creates named exports for top-level properties, so import { appName } from "./config.json" type-checks. The leniency reflects what bundlers accept. Native runtimes accept none of it.
What Bundlers Do with JSON
A bundler usually does not keep a JSON import as a module request. It reads the file, parses it, and inlines the data as a JavaScript value inside the bundle. After that step, the runtime never sees a JSON module. It does no MIME type check, no attribute check, and no separate network request.
The table summarizes how common bundlers handle JSON.
| Bundler | JSON support | Named imports from JSON | Notes |
|---|---|---|---|
| Vite | Built in | Allowed, and tree-shaken | `json.stringify` can emit `JSON.parse("...")`, which parses faster for large files |
| esbuild | Built-in `json` loader | Allowed | Accepts the `with` attribute when bundling |
| webpack 5 | Built in | Warns in strict ESM files | Warns "only default export is available soon" |
| Rollup 4 | Needs `@rollup/plugin-json` | Allowed through the plugin | `output.importAttributesKey` controls `with` or `assert` on external imports |
Bundlers allow named imports so they can tree-shake. import { appName } from "./config.json" lets the bundler drop features and version from the output. That saving is real when the file is large. The cost is that the code depends on the bundler.
Keeping JSON external
Sometimes you want the JSON to stay a separate file. Two common reasons are a config file that operators edit after deployment and a large dataset you don't want inside the main bundle. Mark the file as external, and the bundler leaves the import in the output. Then the attribute has to be present, because the runtime checks it again:
// build.mjs: run with `node build.mjs`
import { build } from "esbuild";
await build({
entryPoints: ["src/main.ts"],
bundle: true,
format: "esm",
platform: "node",
outfile: "dist/main.js",
external: ["./config.json"],
});The output contains import config from "./config.json" with { type: "json" }, so config.json has to sit next to dist/main.js when the program runs. Library builds with Rollup can hit the same issue. If a downstream runtime still expects old syntax, set output.importAttributesKey to choose which keyword the build writes for external imports.
Failure Modes to Watch For
- Passes in the bundle, fails in tests. Test runners that execute ESM natively, such as Node's built-in runner or Vitest in some configurations, do not use the bundler's JSON handling. A named JSON import or a missing attribute breaks there.
- Stale types after a schema change. Editors cache types inferred from JSON. Restart the TypeScript server after you change a large JSON file's structure.
- Huge inferred types. A multi-megabyte JSON file slows type checking, because TypeScript builds a type for the whole file. For large data, declare a small interface and load the file with
fetchorreadFileinstead. - JSON missing from
outDir.tsccopies only JSON files that are imported and that sit insiderootDir. A file loaded by a computed dynamicimport()path is not copied. Add a copy step to the build for those files. - Mixed
assertandwithin dependencies. Older packages that shipassertcan fail in current runtimes and in TypeScript'snodenextmode. Bundling them usually hides the problem, because the bundler inlines the JSON.
Choosing a Configuration
| Situation | `module` / `moduleResolution` | JSON import style |
|---|---|---|
| Node.js app compiled by `tsc` | `nodenext` / `nodenext` | Default import with `with { type: "json" }` (enforced) |
| Browser app built with Vite or webpack | `esnext` / `bundler` | Default import with the attribute, for portability |
| Library published as ESM | `nodenext` / `nodenext` | Strict form, because consumers may not bundle |
| Large data loaded at runtime | Any | Skip JSON modules. Use `fetch` or `readFile` with a declared type |
The rule that holds everywhere: write JSON imports the way the strictest runtime that might execute them requires, and treat bundler leniency as a convenience you avoid depending on.
Exercise
A project uses moduleResolution: "bundler" and contains import { version } from "./config.json";. Vite builds it without errors, but a Node.js script that imports the same source file directly throws an error. Name the two problems in the import and give the corrected line.
Show answer
The import has no with { type: "json" } attribute, so Node.js rejects it. It also uses a named import, which fails at link time because a JSON module has only a default export. TypeScript's bundler mode and Vite accept both forms, so neither tool reported a problem. Corrected: import config from "./config.json" with { type: "json" }; followed by const { version } = config;.
Exercise
You bundle a Node.js service with esbuild and mark ./settings.json as external so operators can edit it after deployment. The service crashes at startup with a "cannot find module" error for settings.json. What went wrong, and what else must the externally kept import include?
Show answer
Because the import is external, the bundle still requests ./settings.json at runtime, relative to the output file. The file was never copied next to dist/main.js. Add a step that copies it there. The kept import must also include with { type: "json" }, because Node.js now loads it as a real JSON module and checks the attribute.