Skip to main content

@babel/plugin-transform-json-modules

import ... with { type: "json" } 声明转换为特定于平台的 API 以读取然后 JSON.parse 导入的文件。

¥Transforms import ... with { type: "json" } declarations to platform-specific API to read and then JSON.parse the imported file.

该插件应用的转换取决于你的顶层 targets 来检测生成的代码是否应与 Node.js、浏览器或两者兼容。当以 Node.js 为目标时,生成的代码也会根据你是否将模块编译为 CommonJS 而改变。

¥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.

提醒

将模块编译为 AMD、SystemJS 或 UMD 时不能使用此插件。

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

提醒

该插件仅转换导入声明,而不转换动态 import() 调用。

¥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-transform-json-modules

用法

¥Usage

¥With a configuration file (Recommended)

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

通过 CLI

¥Via CLI

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

通过 Node API

¥Via Node API

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

选项

¥Options

uncheckedRequire

类型:boolean
默认值:false
添加于 v7.25.0

¥Type: boolean
Default: false
Added in v7.25.0

设置为 true 时,插件将通过直接使用 require 导入 JSON 文件来生成更简单的输出。当针对 CommonJS 时,此选项会导致打包器更容易分析的输出,但不会检查导入的模块是否实际上是 JSON:

¥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" };

输出(不使用 uncheckedRequire: true

¥Out (without uncheckedRequire: true)

const data = JSON.parse(require("fs").readFileSync(require.resolve("./data.json")));

输出(使用 uncheckedRequire: true

¥Out (with uncheckedRequire: true)

const data = require("./data.json");

参考

¥References