有條件偵測程式碼是否使用 bun
執行的建議方式是檢查 Bun
全域變數是否存在。
這類似於檢查 window
變數是否存在以偵測程式碼是否在瀏覽器中執行。
if (typeof Bun !== "undefined") {
// this code will only run when the file is run with Bun
}
在 TypeScript 環境中,除非已全域安裝 bun-types
,否則前述方法將導致型別錯誤。為避免此問題,您可以改為檢查 process.versions
。
if (process.versions.bun) {
// this code will only run when the file is run with Bun
}