Bun 將 TypeScript 視為一等公民。
注意 — 要為 Bun API(如 Bun 全域性物件)新增型別宣告,請按照 簡介 > TypeScript 中的說明進行操作。本頁面介紹 Bun 執行時如何執行 TypeScript 程式碼。
執行 .ts 檔案
Bun 可以直接執行 .ts 和 .tsx 檔案,就像原生 JavaScript 一樣,無需任何額外配置。如果您匯入一個 .ts 或 .tsx 檔案(或匯出這些檔案的 npm 模組),Bun 會在內部將其轉換為 JavaScript,然後執行該檔案。
注意 — 與其他構建工具類似,Bun 不會進行型別檢查。如果您想捕獲靜態型別錯誤,請使用 tsc(官方 TypeScript CLI)。
是否仍需要轉譯? — 由於 Bun 可以直接執行 TypeScript,您可能無需在生產環境中轉譯 TypeScript。Bun 在內部轉譯它執行的每個檔案(包括 .js 和 .ts),因此直接執行 .ts/.tsx 原始檔的額外開銷可以忽略不計。
但是,如果您將 Bun 用作開發工具,但在生產環境中仍以 Node.js 或瀏覽器為目標,則仍需要轉譯。
路徑對映
在解析模組時,Bun 的執行時會遵循 tsconfig.json 中定義的 compilerOptions.paths 中的路徑對映。沒有其他執行時會這樣做。
考慮以下 tsconfig.json。
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"data": ["./data.ts"]
}
}
}
Bun 將使用 baseUrl 來解析模組路徑。
// resolves to ./src/components/Button.tsx
import { Button } from "components/Button.tsx";
Bun 還會正確解析來自 "data" 的匯入。
import { foo } from "data";
console.log(foo); // => "Hello world!"
export const foo = "Hello world!"
實驗性裝飾器
Bun 支援 TypeScript 5.0 之前的實驗性裝飾器語法。
// Simple logging decorator
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with:`, args);
return originalMethod.apply(this, args);
};
}
class Example {
@log
greet(name: string) {
return `Hello ${name}!`;
}
}
// Usage
const example = new Example();
example.greet("world"); // Logs: "Calling greet with: ['world']"
要啟用它,請在 tsconfig.json 中新增 "experimentalDecorators": true。
{
"compilerOptions": {
// ... rest of your config
"experimentalDecorators": true,
},
}
我們通常不建議在新程式碼庫中使用此功能,但許多現有程式碼庫已經依賴它。
emitDecoratorMetadata
Bun 支援 tsconfig.json 中的 emitDecoratorMetadata。這可以在原始檔中為被裝飾的聲明發出設計時型別元資料。
import "reflect-metadata";
class User {
id: number;
name: string;
}
function Injectable(target: Function) {
// Get metadata about constructor parameters
const params = Reflect.getMetadata("design:paramtypes", target);
console.log("Dependencies:", params); // [User]
}
@Injectable
class UserService {
constructor(private user: User) {}
}
// Creates new UserService instance with dependencies
const container = new UserService(new User());
要啟用它,請在 tsconfig.json 中新增 "emitDecoratorMetadata": true。
{
"compilerOptions": {
// ... rest of your config
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
},
}