執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

匯入 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。