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;查看 文檔 > API > YAML 了解 Bun 中 YAML 支持的完整文檔。