关于 bun
这项技能指导 JavaScript 和 TypeScript 项目使用 Bun 作为运行时和包管理器。它将常见的 Node.js、包管理、测试和构建命令映射到 Bun 用法,并介绍 Bun 专用 API。
主要功能
- 01将常见命令映射到 Bun
- 02使用 Bun 专用运行时 API
- 03通过 bun:test 运行测试
- 04用 Bun 提供前端文件
- 05自动加载 .env 文件
适用场景
- 01用 Bun 运行 TypeScript 文件
- 02安装依赖并运行脚本
- 03使用 bun:test 测试项目
- 04通过 Bun.serve() 构建前端
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ brianlovin/ agent-config --skill bun安装后在 Claude Code 中输入/bun确认已加载。
详细介绍
Bun 运行时
默认使用 Bun 作为 JavaScript/TypeScript 运行时和包管理器。
命令映射
| 不要使用 | 改用 |
|---|---|
node file.ts | bun file.ts |
ts-node file.ts | bun file.ts |
npm install | bun install |
npm run script | bun run script |
jest / vitest | bun test |
webpack / esbuild | bun build |
Bun 会自动加载 .env 文件——不要使用 dotenv。
Bun 专属 API
优先使用以下 API,而非对应的 Node.js API:
| API | 用途 | 不要使用 |
|---|---|---|
Bun.serve() | 支持 WebSocket、HTTPS 和路由的 HTTP 服务 | express |
bun:sqlite | SQLite 数据库 | better-sqlite3 |
Bun.redis | Redis 客户端 | ioredis |
Bun.sql | Postgres 客户端 | pg, postgres.js |
Bun.file() | 文件操作 | node:fs readFile/writeFile |
Bun.$\cmd`` | Shell 命令 | execa |
WebSocket | WebSocket 客户端(内置) | ws |
测试
使用 bun:test 编写测试:
import { test, expect } from "bun:test";
test("description", () => {
expect(1).toBe(1);
});
使用 bun test 运行。
前端开发
使用 HTML 导入和 Bun.serve(),而不是 Vite。支持 React、CSS 和 Tailwind。
服务端:
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": {
GET: (req) => Response.json({ id: req.params.id }),
},
},
development: { hmr: true, console: true }
})
HTML 文件:
<html>
<body>
<script type="module" src="./app.tsx"></script>
</body>
</html>
Bun 的打包器会自动转译 .tsx、.jsx 和 .js。CSS 通过 <link> 标签打包。
使用 bun --hot ./server.ts 启动 HMR。
文档
如需详细的 API 文档,请参阅 node_modules/bun-types/docs/**.md。
评论
支持 Markdown