开始使用5 分钟上手
5 分钟上手
安装 Bun,创建一个 TypeScript HTTP 服务并运行测试
最后更新于
0. 你将得到什么
完成后,你会有一个无需额外框架的 TypeScript HTTP 服务、一个测试文件,以及一套最小项目结构。
1. 安装并验证
curl -fsSL https://bun.com/install | bash
bun --version
bun --revisionLinux 需要 unzip。若 bun 找不到,重开终端并确认 ~/.bun/bin 已加入 PATH。
2. 创建项目
mkdir hello-bun
cd hello-bun
bun init -y创建 server.ts:
const server = Bun.serve({
port: 3000,
routes: {
'/': new Response('Hello from Bun!'),
'/health': Response.json({ ok: true }),
},
});
console.log(`Listening on ${server.url}`);运行:
bun run server.ts
curl http://localhost:3000/health
# {"ok":true}3. 添加测试
创建 math.ts:
export function add(a: number, b: number) {
return a + b;
}创建 math.test.ts:
import { expect, test } from 'bun:test';
import { add } from './math';
test('adds two numbers', () => {
expect(add(2, 3)).toBe(5);
});bun test4. 固化脚本
{
"scripts": {
"dev": "bun --watch server.ts",
"start": "bun run server.ts",
"test": "bun test"
}
}以后只需:
bun run dev
bun run test不要把开发服务器直接当生产方案
部署前仍需确认目标平台、进程守护、日志、健康检查、环境变量和优雅退出。Bun 能运行服务,不等于自动解决运维。
下一步
- 不清楚 Bun 与 Node.js、npm、Jest 的关系:读 心智模型。
- 已经有 Node.js 项目:读 从 Node.js 迁移。
- 想系统掌握命令:从 运行时 开始。