Skip to content

Bun はネイティブに .yaml および .yml のインポートをサポートしています。

yaml
database:
  host: localhost
  port: 5432
  name: myapp

server:
  port: 3000
  timeout: 30

features:
  auth: true
  rateLimit: true

他のソースファイルと同様にファイルをインポートします。

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

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

名前付きインポートを使用してトップレベルのプロパティを分割代入することもできます。

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

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

Bun は Import Attributes 構文もサポートしています。

ts
import config from "./config.yaml" with { type: "yaml" };

config.database.port; // => 5432

ランタイムで YAML 文字列を解析するには、Bun.YAML.parse() を使用します。

ts
const yamlString = `
name: John Doe
age: 30
hobbies:
  - reading
  - coding
`;

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

TypeScript サポート

YAML インポートの TypeScript サポートを追加するには、YAML ファイル名に .d.ts を追加した宣言ファイルを作成します(例:config.yamlconfig.yaml.d.ts)。

ts
const contents: {
  database: {
    host: string;
    port: number;
    name: string;
  };
  server: {
    port: number;
    timeout: number;
  };
  features: {
    auth: boolean;
    rateLimit: boolean;
  };
};

export = contents;

Bun の YAML サポートの完全なドキュメントについては、ドキュメント > API > YAML を参照してください。

Bun by www.bunjs.com.cn 編集