> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 检测代码何时在 Bun 中执行

检测代码何时在 Bun 中执行的推荐方式是检查 `process.versions.bun`。这在 JavaScript 和 TypeScript 中都适用，无需任何额外的类型定义。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
if (process.versions.bun) {
  // 这段代码只会在文件通过 Bun 运行时执行
}
```

***

另外，你也可以检查全局对象 `Bun` 是否存在。这类似于检查 `window` 变量是否存在以检测代码是否在浏览器中执行。

<Note>
  除非安装了 `@types/bun`，否则此方法在 TypeScript 中会导致类型错误。你可以通过运行 `bun add -d @types/bun` 来安装它。
</Note>

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
if (typeof Bun !== "undefined") {
  // 这段代码只会在文件通过 Bun 运行时执行
}
```
