> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/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={null}
    bun init my-app
    ```

    `bun init` 会提示你选择一个模板：`Blank`、`React` 或 `Library`。本教程选择 `Blank`。

    ```bash terminal icon="terminal" theme={null}
    bun init my-app
    ```

    ```txt theme={null}
    ✓ 选择项目模板：Blank

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

    新的 `my-app` 目录包含一个基本的 Bun 应用。
  </Step>

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

    ```bash terminal icon="terminal" theme={null}
    cd my-app
    bun run index.ts
    ```

    ```txt theme={null}
    Hello via Bun!
    ```
  </Step>

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

    ```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": () => new Response('Bun!'),
      }
    });

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

    再次运行 `index.ts`。

    ```bash terminal icon="terminal" theme={null}
    bun run index.ts
    ```

    ```txt theme={null}
    Listening on http://localhost:3000/
    ```

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

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

      要修复此问题，首先将 `@types/bun` 安装为开发依赖。

      ```bash terminal icon="terminal" theme={null}
      bun add -d @types/bun
      ```

      然后在 `tsconfig.json` 的 `compilerOptions` 中添加以下内容：

      ```json tsconfig.json icon="file-json" theme={null}
      {
        "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={null}
    bun add figlet
    bun add -d @types/figlet # 仅 TypeScript 用户需要
    ```

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

    ```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    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}`);
    ```

    再次运行 `index.ts`。

    ```bash terminal icon="terminal" theme={null}
    bun run index.ts
    ```

    ```txt theme={null}
    Listening on http://localhost:3000/
    ```

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

    ```txt theme={null}
    ____              _
    | __ ) _   _ _ __ | |
    |  _ \| | | | '_ \| |
    | |_) | |_| | | | |_|
    |____/ \__,_|_| |_(_)
    ```
  </Step>

  <Step title="第 5 步">
    现在添加一些 HTML。创建一个名为 `index.html` 的新文件：

    ```html index.html icon="file-code" theme={null}
    <!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/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
    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}`);
    ```

    再次运行 `index.ts`。

    ```bash terminal icon="terminal" theme={null}
    bun run index.ts
    ```

    ```txt theme={null}
    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={null}
{
  "name": "my-app",
  "module": "index.ts",
  "type": "module",
  "private": true,
  "scripts": { // [!code ++]
    "start": "bun run index.ts" // [!code ++]
  }, // [!code ++]
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^6"
  }
}
```

然后使用 `bun run start` 运行它。

```bash terminal icon="terminal" theme={null}
bun run start
```

```txt theme={null}
Listening on http://localhost:3000/
```

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