Bun 原生支援 .yaml 和 .yml 匯入。
database:
host: localhost
port: 5432
name: myapp
server:
port: 3000
timeout: 30
features:
auth: true
rateLimit: true
像匯入其他原始檔一樣匯入檔案。
import config from "./config.yaml";
config.database.host; // => "localhost"
config.server.port; // => 3000
config.features.auth; // => true
您還可以使用具名匯入來解構頂層屬性
import { database, server, features } from "./config.yaml";
console.log(database.name); // => "myapp"
console.log(server.timeout); // => 30
console.log(features.rateLimit); // => true
Bun 還支援 匯入屬性 語法
import config from "./config.yaml" with { type: "yaml" };
config.database.port; // => 5432
要在執行時解析 YAML 字串,請使用 Bun.YAML.parse()
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 支援,請建立一個以 .d.ts 結尾的宣告檔案(例如,config.yaml → config.yaml.d.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。