@babel/plugin-transform-json-modules
Transforms import ... with { type: "json" }
declarations to platform-specific API to read and then JSON.parse
the imported file.
The transformation applied by this plugin depends on your top-level targets
to detect whether the generated code should be compatible with Node.js, browsers, or both. When targeting Node.js, the generated code will also change depending on whether you are compiling modules to CommonJS or not.
This plugin cannot be used when compiling modules to AMD, SystemJS, or UMD.
This plugin only transforms import decalarations and not dynamic import()
calls.
Example
import data from "./data.json" with { type: "json" };
will be transformed to
- Browsers
- Node.js (ESM)
- Node.js (CommonJS)
- Browsers and Node.js (ESM)
const data = await fetch(import.meta.resolve("./data.json")).then(r => r.json());
import { readFileSync as _readFileSync } from "fs";
const data = JSON.parse(_readFileSync(new URL(import.meta.resolve("./data.json"))));
"use strict";
const data = JSON.parse(require("fs").readFileSync(require.resolve("./data.json")));
const data = await (
typeof process === "object" && process.versions?.node
? import("fs").then(fs => fs.promises.readFile(new URL(import.meta.resolve("./data.json")))).then(JSON.parse)
: fetch(import.meta.resolve("./data.json")).then(r => r.json())
);
Installation
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-json-modules
yarn add --dev @babel/plugin-transform-json-modules
pnpm add --save-dev @babel/plugin-transform-json-modules
Usage
With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-json-modules"]
}
Via CLI
babel --plugins=@babel/plugin-transform-json-modules script.js
Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-json-modules"],
});
Options
uncheckedRequire
Type: boolean
Default: false
Added in v7.25.0
When set to true
, the plugin will generate a simpler output by using require
directly to import the JSON file. When targeting CommonJS, this option leads to output that is easier to analyze for bundlers but doesn't check that the module being imported is actually JSON:
In
import data from "./data.json" with { type: "json" };
Out (without uncheckedRequire: true
)
const data = JSON.parse(require("fs").readFileSync(require.resolve("./data.json")));
Out (with uncheckedRequire: true
)
const data = require("./data.json");