Skip to main content

概述

使用 Bun.serve 构建一个最小 HTTP 服务器,在本地运行它,然后通过安装一个包来进一步扩展。
前提条件:已安装 Bun 并可在 PATH 中使用。请参阅安装进行设置。

1

第 1 步

使用 bun init 初始化一个新项目。
terminal
bun init 会提示你选择一个模板:BlankReactLibrary。本教程选择 Blank
terminal
新的 my-app 目录包含一个基本的 Bun 应用。
2

第 2 步

使用 bun run 运行 index.ts
terminal
3

第 3 步

index.ts 的内容替换为以下代码:
index.ts
再次运行 index.ts
terminal
访问 http://localhost:3000 测试服务器。你应该能看到显示 "Bun!" 的页面。
bun init 会安装 Bun 的 TypeScript 声明并配置 tsconfig.json。如果你在现有项目中尝试使用 Bun,可能会在 Bun 全局对象上看到类型错误。要修复此问题,首先将 @types/bun 安装为开发依赖。
terminal
然后在 tsconfig.jsoncompilerOptions 中添加以下内容:
tsconfig.json
4

第 4 步

安装 figlet 包及其类型声明。Figlet 是一个将字符串转换为 ASCII 艺术的工具。
terminal
更新 index.ts,在 routes 中使用 figlet
index.ts
再次运行 index.ts
terminal
访问 http://localhost:3000/figlet 测试服务器。你应该能看到以 ASCII 艺术形式显示的 "Bun!"
5

第 5 步

现在添加一些 HTML。创建一个名为 index.html 的新文件:
index.html
然后,在 index.ts 中导入此文件,并在根路由 / 中提供它。
index.ts
再次运行 index.ts
terminal
访问 http://localhost:3000 测试服务器。你应该能看到静态 HTML 页面。
你已经使用 Bun 构建了一个 HTTP 服务器并安装了一个包。

运行脚本

Bun 还可以执行 package.json 中的 "scripts"。添加以下脚本:
package.json
然后使用 bun run start 运行它。
terminal
⚡️ 性能bun runnpm run 快约 28 倍(6ms 对 170ms 的额外开销)。