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); // => trueBun は 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.yaml → config.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 を参照してください。