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.

caution

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

caution

这个插件只会转换导入声明,不会转换动态的 import() 调用。

示例​

🌐 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:

在

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

输出(不包括 uncheckedRequire: true)

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

外出(使用 uncheckedRequire: true)

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

参考​

🌐 References