⚡ 极速运行时
Bun 基于 Apple 的 JavaScriptCore 引擎,专为性能优化。启动时间比 Node.js 快 4 倍,测试运行快 5 倍。
零配置 TypeScript
typescript
// index.ts - 直接运行,无需配置
interface User {
name: string;
age: number;
}
const greet = (user: User): string => {
return `Hello, ${user.name}!`;
};
console.log(greet({ name: "Bun", age: 1 }));
bash
# 直接运行 TypeScript
bun run index.ts
JSX / React 支持
tsx
// App.tsx - 无需 Babel 配置
function App() {
return Hello, Bun!
;
}
export default App;
📦 包管理器
Bun 的包管理器比 npm 快 30 倍,使用全局缓存和优化的依赖解析。
极速安装
比 npm 快 30 倍
Workspaces
Monorepo 原生支持
bun audit
安全漏洞检测
bun publish
一键发布 npm 包
bash
# 安装依赖
bun install
# 添加依赖
bun add react
# 开发依赖
bun add -d typescript
# 全局安装
bun add -g prettier
🧪 测试框架
Jest 兼容的测试框架,内置覆盖率、快照测试、Mock 功能。
typescript
// math.test.ts
import { expect, test, describe } from "bun:test";
describe("Math", () => {
test("addition", () => {
expect(1 + 1).toBe(2);
});
test("async", async () => {
const result = await Promise.resolve(42);
expect(result).toBe(42);
});
});
bash
# 运行测试
bun test
# 监听模式
bun test --watch
# 覆盖率
bun test --coverage
🔨 打包器
内置打包器,支持前端和后端代码打包,可编译为独立可执行文件。
typescript
// build.ts
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "node", // 或 "browser", "bun"
minify: true,
splitting: true,
});
跨平台编译
bash
# 编译为可执行文件
bun build ./src/index.ts --compile --outfile=myapp
# 跨平台编译
bun build ./src/index.ts --compile --target=linux-x64 --outfile=myapp-linux
bun build ./src/index.ts --compile --target=windows-x64 --outfile=myapp.exe
🌐 内置数据库支持
SQLite
bun:sqlite 内置
PostgreSQL
Bun.sql API
MySQL
Bun.sql 支持
Redis
Bun.redis API
typescript
// SQLite - 零依赖
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
const users = db.query("SELECT * FROM users").all();
🔥 热重载
开发模式下自动重载,无需手动重启。
bash
# 热重载模式
bun --hot run server.ts
# 监听模式(文件变化重启)
bun --watch run server.ts