> ## 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.serve` 构建一个简约的 HTTP 服务器，在本地运行它，然后通过安装一个包来扩展它。

<Info>先决条件：已安装 Bun 并且可在您的 `PATH` 中访问。有关安装，请参见 [安装](/installation)。</Info>

***

<Steps>
  <Step title="步骤 1">
    使用 `bun init` 初始化一个新项目。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun init my-app
    ```

    它会提示您选择一个模板，可以是 `Blank`、`React` 或 `Library`。本指南中，我们选择 `Blank`。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun init my-app
    ```

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    ✓ 选择一个项目模板：Blank

    - .gitignore
    - CLAUDE.md
    - .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
    - index.ts
    - tsconfig.json (用于编辑器自动补全)
    - README.md
    ```

    这将自动创建一个包含基础 Bun 应用的 `my-app` 目录。
  </Step>

  <Step title="步骤 2">
    使用 `bun run index.ts` 运行 `index.ts` 文件。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    cd my-app
    bun run index.ts
    ```

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    Hello via Bun!
    ```

    您应该会在控制台看到输出 `"Hello via Bun!"`。
  </Step>

  <Step title="步骤 3">
    将 `index.ts` 的内容替换为以下代码：

    ```ts index.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": () => new Response('Bun!'),
      }
    });

    console.log(`Listening on ${server.url}`);
    ```

    再次使用 `bun run index.ts` 运行该文件。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun run index.ts
    ```

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    Listening on http://localhost:3000
    ```

    访问 [`http://localhost:3000`](http://localhost:3000) 测试服务器。您应该看到一个显示 `"Bun!"` 的页面。

    <Accordion title="在 Bun 中看到 TypeScript 错误？">
      如果您使用了 `bun init`，Bun 会自动安装 Bun 的 TypeScript 声明并配置您的 `tsconfig.json`。如果您在现有项目中尝试 Bun，可能会看到 `Bun` 全局的类型错误。

      要解决此问题，首先安装 `@types/bun` 作为开发依赖。

      ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
      bun add -d @types/bun
      ```

      然后在 `tsconfig.json` 的 `compilerOptions` 中添加以下配置：

      ```json tsconfig.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
      {
        "compilerOptions": {
          "lib": ["ESNext"],
          "target": "ESNext",
          "module": "Preserve",
          "moduleDetection": "force",
          "moduleResolution": "bundler",
          "allowImportingTsExtensions": true,
          "verbatimModuleSyntax": true,
          "noEmit": true
        }
      }
      ```
    </Accordion>
  </Step>

  <Step title="步骤 4">
    安装 `figlet` 包及其类型声明。Figlet 是一个将字符串转换为 ASCII 艺术的工具。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun add figlet
    bun add -d @types/figlet # 仅限 TypeScript 用户
    ```

    更新 `index.ts`，在 `routes` 中使用 `figlet`。

    ```ts index.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
    import figlet from 'figlet'; // [!code ++]

    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": () => new Response('Bun!'),
        "/figlet": () => { // [!code ++]
          const body = figlet.textSync('Bun!'); // [!code ++]
          return new Response(body); // [!code ++]
        } // [!code ++]
      }
    });

    console.log(`Listening on ${server.url}`);
    ```

    再次使用 `bun run index.ts` 运行该文件。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun run index.ts
    ```

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    Listening on http://localhost:3000
    ```

    访问 [`http://localhost:3000/figlet`](http://localhost:3000/figlet) 测试服务器。您应该看到以 ASCII 艺术形式显示的 `"Bun!"`。

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    ____              _
    | __ ) _   _ _ __ | |
    |  _ \| | | | '_ \| |
    | |_) | |_| | | | |_|
    |____/ \__,_|_| |_(_)
    ```
  </Step>

  <Step title="步骤 5">
    让我们添加一些 HTML。创建一个新文件 `index.html`，并添加以下代码：

    ```html index.html icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bun</title>
      </head>
      <body>
        <h1>Bun!</h1>
      </body>
    </html>
    ```

    然后，在 `index.ts` 中导入此文件，并从根路由 `/` 提供它。

    ```ts index.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
    import figlet from 'figlet';
    import index from './index.html'; // [!code ++]

    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": index, // [!code ++]
        "/figlet": () => {
          const body = figlet.textSync('Bun!');
          return new Response(body);
        }
      }
    });

    console.log(`Listening on ${server.url}`);
    ```

    再次使用 `bun run index.ts` 运行该文件。

    ```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
    bun run index.ts
    ```

    ```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
    Listening on http://localhost:3000
    ```

    访问 [`http://localhost:3000`](http://localhost:3000) 测试服务器。您应该看到该静态 HTML 页面。
  </Step>
</Steps>

🎉 恭喜！您已使用 Bun 构建了一个 HTTP 服务器并安装了一个包。

***

## 运行脚本

Bun 也可以执行 `package.json` 中的 `"scripts"`。添加以下脚本：

```json package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "name": "quickstart",
  "module": "index.ts",
  "type": "module",
  "private": true,
  "scripts": { // [!code ++]
    "start": "bun run index.ts" // [!code ++]
  }, // [!code ++]
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5"
  }
}
```

然后通过 `bun run start` 运行它。

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run start
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
正在监听 http://localhost:3000
```

<Note>⚡️ **性能** — `bun run` 的速度大约是 `npm run` 的 28 倍（6ms 对比 170ms 的开销）。</Note>
