執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

TypeScript

在 Bun 中使用 TypeScript,包括型別定義和編譯器選項

要獲取 Bun 內建 API 的 TypeScript 型別定義,請安裝 @types/bun。

terminal
bun add -d @types/bun # 開發相依

現在,你可以在 TypeScript 檔案中引用 Bun 全域性變數,編輯器不會再報錯。

推薦的 compilerOptions

Bun 支援頂層 await、JSX 以及帶有 .ts 副檔名的匯入,而 TypeScript 預設不允許這些特性。在 Bun 專案中使用以下 compilerOptions,這樣 TypeScript 就不會針對這些特性發出警告。

tsconfig.json
{
  "compilerOptions": {
    // 環境設定 & 最新特性
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleDetection": "force",
    "jsx": "react-jsx",
    "allowJs": true,
    "types": ["bun"],

    // 打包器模式
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,

    // 最佳實踐
    "strict": true,
    "skipLibCheck": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,

    // 一些更嚴格的標誌(預設停用)
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noPropertyAccessFromIndexSignature": false
  }
}

在新目錄中執行 bun init 會為你生成此 tsconfig.json 檔案。

terminal
bun init

TypeScript 6 和 7

如果你使用的是 TypeScript 6.0 或更高版本,還需要在 compilerOptions 中新增 "types": ["bun"]。請參閱TypeScript 6 和 7。