Skip to main content

@babel/plugin-proposal-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.

caution

This plugin cannot be used when compiling modules to AMD, SystemJS, or UMD.

caution

This plugin only transforms import decalarations and not dynamic import() calls.

Example

input.js
import data from "./data.json" with { type: "json" };

will be transformed to

output.js
const data = await fetch(import.meta.resolve("./data.json")).then(r => r.json());

Installation

npm install --save-dev @babel/plugin-proposal-json-modules

Usage

babel.config.json
{
"plugins": [
"@babel/plugin-proposal-json-modules"
]
}

Via CLI

Shell
babel --plugins=@babel/plugin-proposal-json-modules script.js

Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: [
"@babel/plugin-proposal-json-modules"
],
});

References