概览
使用Bun.serve 构建一个简约的 HTTP 服务器,在本地运行它,然后通过安装一个包来扩展它。
先决条件:已安装 Bun 并且可在您的
PATH 中访问。有关安装,请参见 安装。1
步骤 1
使用 它会提示您选择一个模板,可以是 这将自动创建一个包含基础 Bun 应用的
bun init 初始化一个新项目。terminal
Blank、React 或 Library。本指南中,我们选择 Blank。terminal
my-app 目录。2
步骤 2
使用 您应该会在控制台看到输出
bun run index.ts 运行 index.ts 文件。terminal
"Hello via Bun!"。3
步骤 3
将
index.ts再次使用 访问
index.ts 的内容替换为以下代码:bun run index.ts 运行该文件。terminal
http://localhost:3000 测试服务器。您应该能看到一个显示 "Bun!" 的简单页面。在 Bun 中看到 TypeScript 错误?
在 Bun 中看到 TypeScript 错误?
如果您使用了 然后在
bun init,Bun 会自动安装 Bun 的 TypeScript 声明并配置您的 tsconfig.json。如果您在现有项目中尝试 Bun,可能会看到 Bun 全局的类型错误。要解决此问题,首先安装 @types/bun 作为开发依赖。terminal
tsconfig.json 的 compilerOptions 中添加以下配置:tsconfig.json
4
步骤 4
安装 更新
index.ts再次使用 访问
figlet 包及其类型声明。Figlet 是一个将字符串转换为 ASCII 艺术的工具。terminal
index.ts,在 routes 中使用 figlet。bun run index.ts 运行该文件。terminal
http://localhost:3000/figlet 测试服务器。您应该看到一段以 ASCII 艺术形式显示的 "Bun!"。5
步骤 5
让我们添加一些 HTML。创建一个新文件 然后,在
index.ts再次使用 访问
index.html,并添加以下代码:index.html
index.ts 中导入此文件,并从根路由 / 提供它。bun run index.ts 运行该文件。terminal
http://localhost:3000 测试服务器。您应该看到该静态 HTML 页面。运行脚本
Bun 也可以执行package.json 中的 "scripts"。添加以下脚本:
package.json
bun run start 运行它。
terminal
⚡️ 性能 —
bun run 的速度大约是 npm run 的 28 倍(6ms 对比 170ms 的开销)。