在 Bun 中执行代码时进行条件检测的推荐方法是检查全局变量 Bun
是否存在。
这类似于在浏览器中检测 window
变量是否存在来判断代码是否在浏览器中执行。
if (typeof Bun !== "undefined") {
// this code will only run when the file is run with Bun
}
在 TypeScript 环境中,如果不安装 @types/bun
,上述方法将导致类型错误。为避免这种情况,您可以改用检查 process.versions
。
if (process.versions.bun) {
// this code will only run when the file is run with Bun
}