Skip to content

概述

使用 Bun.serve 构建一个最小化的 HTTP 服务器,在本地运行它,然后通过安装包来扩展它。

::: 前提条件:已安装 Bun 并可在 PATH 上使用。请参阅 安装 进行设置。 :::


使用 bun init 初始化一个新项目。

bash
bun init my-app

它会提示你选择一个模板,可以是 BlankReactLibrary。在本指南中,我们选择 Blank

bash
bun init my-app
bash
 选择一个项目模板: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 目录。

使用 bun run index.ts 运行 index.ts 文件。

bash
cd my-app
bun run index.ts
bash
Hello via Bun!

你应该会看到控制台输出显示 "Hello via Bun!"

index.ts 的内容替换为以下代码:

ts
const server = Bun.serve({
  port: 3000,
  routes: {
    "/": () => new Response('Bun!'),
  }
});

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

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

bash
bun run index.ts
bash
Listening on http://localhost:3000

访问 http://localhost:3000 测试服务器。你应该会看到一个显示 "Bun!" 的简单页面。

在 Bun 上看到 TypeScript 错误?

如果你使用了 bun init,Bun 将自动安装 Bun 的 TypeScript 声明并配置你的 tsconfig.json。如果你在现有项目中尝试 Bun,可能会在 Bun 全局对象上看到类型错误。

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

bash
bun add -d @types/bun

然后将以下内容添加到 tsconfig.json 中的 compilerOptions

json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleDetection": "force",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true
  }
}

安装 figlet 包及其类型声明。Figlet 是一个将字符串转换为 ASCII 艺术的实用工具。

bash
bun add figlet
bun add -d @types/figlet # 仅限 TypeScript 用户

更新 index.tsroutes 中使用 figlet

ts
import figlet from 'figlet';

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

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

bash
bun run index.ts
bash
Listening on http://localhost:3000

访问 http://localhost:3000/figlet 测试服务器。你应该会看到一个显示 ASCII 艺术 "Bun!" 的简单页面。

bash
____              _
| __ ) _   _ _ __ | |
|  _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)

让我们添加一些 HTML。创建一个名为 index.html 的新文件并添加以下代码:

html
<!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
import figlet from 'figlet';
import index from './index.html'; 

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

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

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

bash
bun run index.ts
txt
Listening on http://localhost:3000

访问 http://localhost:3000 测试服务器。你应该会看到静态 HTML 页面。

🎉 恭喜你!你已经使用 Bun 构建了一个简单的 HTTP 服务器并安装了一个包。


运行脚本

Bun 还可以执行 package.json 中的 "scripts"。添加以下脚本:

json
{
  "name": "quickstart",
  "module": "index.ts",
  "type": "module",
  "private": true,
  "scripts": { 
    "start": "bun run index.ts"
  }, 
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5"
  }
}

然后使用 bun run start 运行它。

bash
bun run start
bash
Listening on http://localhost:3000

INFO

性能bun runnpm run 快大约 28 倍(6ms 对比 170ms 的开销)。

Bun学习网由www.bunjs.com.cn整理维护