运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

导入 JSON5 文件

Bun 原生支持导入 .json5 文件。

config.json5
{
  // 允许使用注释
  database: {
    host: "localhost",
    port: 5432,
    name: "myapp",
  },

  server: {
    port: 3000,
    timeout: 30,
  },

  features: {
    auth: true,
    rateLimit: true,
  },
}

像导入其他源文件一样导入该文件。

config.ts
import config from "./config.json5";

config.database.host; // => "localhost"
config.server.port; // => 3000
config.features.auth; // => true

你也可以使用命名导入来解构顶层属性:

config.ts
import { database, server, features } from "./config.json5";

console.log(database.name); // => "myapp"
console.log(server.timeout); // => 30
console.log(features.rateLimit); // => true

如需在运行时解析 JSON5 字符串,请使用 Bun.JSON5.parse():

config.ts
const data = Bun.JSON5.parse(`{
  name: 'John Doe',
  age: 30,
  hobbies: [
    'reading',
    'coding',
  ],
}`);

console.log(data.name); // => "John Doe"
console.log(data.hobbies); // => ["reading", "coding"]

有关 Bun 对 JSON5 的其余支持,请参阅 JSON5。