bun-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese⚡ Bun Development
⚡ Bun 开发
Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by oven-sh/bun.
基于Bun运行时的快速、现代JavaScript/TypeScript开发,灵感来自 oven-sh/bun。
When to Use This Skill
何时使用此技能
Use this skill when:
- Starting new JS/TS projects with Bun
- Migrating from Node.js to Bun
- Optimizing development speed
- Using Bun's built-in tools (bundler, test runner)
- Troubleshooting Bun-specific issues
在以下场景使用此技能:
- 使用Bun启动新的JS/TS项目
- 从Node.js迁移到Bun
- 优化开发速度
- 使用Bun的内置工具(打包器、测试运行器)
- 排查Bun相关的问题
1. Getting Started
1. 快速入门
1.1 Installation
1.1 安装
bash
undefinedbash
undefinedmacOS / Linux
macOS / Linux
curl -fsSL https://bun.sh/install | bash
curl -fsSL https://bun.sh/install | bash
Windows
Windows
powershell -c "irm bun.sh/install.ps1 | iex"
powershell -c "irm bun.sh/install.ps1 | iex"
Homebrew
Homebrew
brew tap oven-sh/bun
brew install bun
brew tap oven-sh/bun
brew install bun
npm (if needed)
npm(如有需要)
npm install -g bun
npm install -g bun
Upgrade
升级
bun upgrade
undefinedbun upgrade
undefined1.2 Why Bun?
1.2 为什么选择Bun?
| Feature | Bun | Node.js |
|---|---|---|
| Startup time | ~25ms | ~100ms+ |
| Package install | 10-100x faster | Baseline |
| TypeScript | Native | Requires transpiler |
| JSX | Native | Requires transpiler |
| Test runner | Built-in | External (Jest, Vitest) |
| Bundler | Built-in | External (Webpack, esbuild) |
| 特性 | Bun | Node.js |
|---|---|---|
| 启动时间 | ~25ms | ~100ms+ |
| 包安装速度 | 快10-100倍 | 基准速度 |
| TypeScript | 原生支持 | 需要转译器 |
| JSX | 原生支持 | 需要转译器 |
| 测试运行器 | 内置 | 需外部工具(Jest、Vitest) |
| 打包器 | 内置 | 需外部工具(Webpack、esbuild) |
2. Project Setup
2. 项目搭建
2.1 Create New Project
2.1 创建新项目
bash
undefinedbash
undefinedInitialize project
初始化项目
bun init
bun init
Creates:
生成的文件:
├── package.json
├── package.json
├── tsconfig.json
├── tsconfig.json
├── index.ts
├── index.ts
└── README.md
└── README.md
With specific template
使用特定模板
bun create <template> <project-name>
bun create <template> <project-name>
Examples
示例
bun create react my-app # React app
bun create next my-app # Next.js app
bun create vite my-app # Vite app
bun create elysia my-api # Elysia API
undefinedbun create react my-app # React应用
bun create next my-app # Next.js应用
bun create vite my-app # Vite应用
bun create elysia my-api # Elysia API
undefined2.2 package.json
2.2 package.json
json
{
"name": "my-bun-project",
"version": "1.0.0",
"module": "index.ts",
"type": "module",
"scripts": {
"dev": "bun run --watch index.ts",
"start": "bun run index.ts",
"test": "bun test",
"build": "bun build ./index.ts --outdir ./dist",
"lint": "bunx eslint ."
},
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}json
{
"name": "my-bun-project",
"version": "1.0.0",
"module": "index.ts",
"type": "module",
"scripts": {
"dev": "bun run --watch index.ts",
"start": "bun run index.ts",
"test": "bun test",
"build": "bun build ./index.ts --outdir ./dist",
"lint": "bunx eslint ."
},
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}2.3 tsconfig.json (Bun-optimized)
2.3 优化后的tsconfig.json
json
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": ["bun-types"]
}
}json
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": ["bun-types"]
}
}3. Package Management
3. 包管理
3.1 Installing Packages
3.1 安装包
bash
undefinedbash
undefinedInstall from package.json
从package.json安装
bun install # or 'bun i'
bun install # 或 'bun i'
Add dependencies
添加依赖
bun add express # Regular dependency
bun add -d typescript # Dev dependency
bun add -D @types/node # Dev dependency (alias)
bun add --optional pkg # Optional dependency
bun add express # 常规依赖
bun add -d typescript # 开发依赖
bun add -D @types/node # 开发依赖(别名)
bun add --optional pkg # 可选依赖
From specific registry
从特定源安装
bun add lodash --registry https://registry.npmmirror.com
bun add lodash --registry https://registry.npmmirror.com
Install specific version
安装特定版本
bun add react@18.2.0
bun add react@latest
bun add react@next
bun add react@18.2.0
bun add react@latest
bun add react@next
From git
从Git安装
bun add github:user/repo
bun add git+https://github.com/user/repo.git
undefinedbun add github:user/repo
bun add git+https://github.com/user/repo.git
undefined3.2 Removing & Updating
3.2 移除与更新包
bash
undefinedbash
undefinedRemove package
移除包
bun remove lodash
bun remove lodash
Update packages
更新包
bun update # Update all
bun update lodash # Update specific
bun update --latest # Update to latest (ignore ranges)
bun update # 更新所有包
bun update lodash # 更新特定包
bun update --latest # 更新到最新版本(忽略版本范围)
Check outdated
检查过时包
bun outdated
undefinedbun outdated
undefined3.3 bunx (npx equivalent)
3.3 bunx(npx的替代工具)
bash
undefinedbash
undefinedExecute package binaries
执行包的二进制文件
bunx prettier --write .
bunx tsc --init
bunx create-react-app my-app
bunx prettier --write .
bunx tsc --init
bunx create-react-app my-app
With specific version
使用特定版本
bunx -p typescript@4.9 tsc --version
bunx -p typescript@4.9 tsc --version
Run without installing
无需安装直接运行
bunx cowsay "Hello from Bun!"
undefinedbunx cowsay "Hello from Bun!"
undefined3.4 Lockfile
3.4 锁文件
bash
undefinedbash
undefinedbun.lockb is a binary lockfile (faster parsing)
bun.lockb是二进制锁文件(解析速度更快)
To generate text lockfile for debugging:
生成文本锁文件用于调试:
bun install --yarn # Creates yarn.lock
bun install --yarn # 生成yarn.lock
Trust existing lockfile
信任已存在的锁文件
bun install --frozen-lockfile
---bun install --frozen-lockfile
---4. Running Code
4. 运行代码
4.1 Basic Execution
4.1 基本执行
bash
undefinedbash
undefinedRun TypeScript directly (no build step!)
直接运行TypeScript(无需构建步骤!)
bun run index.ts
bun run index.ts
Run JavaScript
运行JavaScript
bun run index.js
bun run index.js
Run with arguments
带参数运行
bun run server.ts --port 3000
bun run server.ts --port 3000
Run package.json script
运行package.json中的脚本
bun run dev
bun run build
bun run dev
bun run build
Short form (for scripts)
简写形式(针对脚本)
bun dev
bun build
undefinedbun dev
bun build
undefined4.2 Watch Mode
4.2 监听模式
bash
undefinedbash
undefinedAuto-restart on file changes
文件变化时自动重启
bun --watch run index.ts
bun --watch run index.ts
With hot reloading
启用热重载
bun --hot run server.ts
undefinedbun --hot run server.ts
undefined4.3 Environment Variables
4.3 环境变量
typescript
// .env file is loaded automatically!
// Access environment variables
const apiKey = Bun.env.API_KEY;
const port = Bun.env.PORT ?? "3000";
// Or use process.env (Node.js compatible)
const dbUrl = process.env.DATABASE_URL;bash
undefinedtypescript
// .env文件会自动加载!
// 访问环境变量
const apiKey = Bun.env.API_KEY;
const port = Bun.env.PORT ?? "3000";
// 也可以使用process.env(兼容Node.js)
const dbUrl = process.env.DATABASE_URL;bash
undefinedRun with specific env file
使用特定环境变量文件运行
bun --env-file=.env.production run index.ts
---bun --env-file=.env.production run index.ts
---5. Built-in APIs
5. 内置API
5.1 File System (Bun.file)
5.1 文件系统(Bun.file)
typescript
// Read file
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const buffer = await file.arrayBuffer();
// File info
console.log(file.size); // bytes
console.log(file.type); // MIME type
// Write file
await Bun.write("./output.txt", "Hello, Bun!");
await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));
// Stream large files
const reader = file.stream();
for await (const chunk of reader) {
console.log(chunk);
}typescript
// 读取文件
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const buffer = await file.arrayBuffer();
// 文件信息
console.log(file.size); // 字节数
console.log(file.type); // MIME类型
// 写入文件
await Bun.write("./output.txt", "Hello, Bun!");
await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));
// 流式处理大文件
const reader = file.stream();
for await (const chunk of reader) {
console.log(chunk);
}5.2 HTTP Server (Bun.serve)
5.2 HTTP服务器(Bun.serve)
typescript
const server = Bun.serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response("Hello World!");
}
if (url.pathname === "/api/users") {
return Response.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]);
}
return new Response("Not Found", { status: 404 });
},
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
},
});
console.log(`Server running at http://localhost:${server.port}`);typescript
const server = Bun.serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response("Hello World!");
}
if (url.pathname === "/api/users") {
return Response.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]);
}
return new Response("Not Found", { status: 404 });
},
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
},
});
console.log(`Server running at http://localhost:${server.port}`);5.3 WebSocket Server
5.3 WebSocket服务器
typescript
const server = Bun.serve({
port: 3000,
fetch(req, server) {
// Upgrade to WebSocket
if (server.upgrade(req)) {
return; // Upgraded
}
return new Response("Upgrade failed", { status: 500 });
},
websocket: {
open(ws) {
console.log("Client connected");
ws.send("Welcome!");
},
message(ws, message) {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
},
close(ws) {
console.log("Client disconnected");
},
},
});typescript
const server = Bun.serve({
port: 3000,
fetch(req, server) {
// 升级为WebSocket
if (server.upgrade(req)) {
return; // 已升级
}
return new Response("Upgrade failed", { status: 500 });
},
websocket: {
open(ws) {
console.log("Client connected");
ws.send("Welcome!");
},
message(ws, message) {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
},
close(ws) {
console.log("Client disconnected");
},
},
});5.4 SQLite (Bun.sql)
5.4 SQLite(Bun.sql)
typescript
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
// Create table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Insert
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");
// Query
const query = db.prepare("SELECT * FROM users WHERE name = ?");
const user = query.get("Alice");
console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }
// Query all
const allUsers = db.query("SELECT * FROM users").all();typescript
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
// 创建表
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// 插入数据
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");
// 查询数据
const query = db.prepare("SELECT * FROM users WHERE name = ?");
const user = query.get("Alice");
console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }
// 查询所有数据
const allUsers = db.query("SELECT * FROM users").all();5.5 Password Hashing
5.5 密码哈希
typescript
// Hash password
const password = "super-secret";
const hash = await Bun.password.hash(password);
// Verify password
const isValid = await Bun.password.verify(password, hash);
console.log(isValid); // true
// With algorithm options
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 12,
});typescript
// 哈希密码
const password = "super-secret";
const hash = await Bun.password.hash(password);
// 验证密码
const isValid = await Bun.password.verify(password, hash);
console.log(isValid); // true
// 指定算法选项
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 12,
});6. Testing
6. 测试
6.1 Basic Tests
6.1 基础测试
typescript
// math.test.ts
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
describe("Math operations", () => {
it("adds two numbers", () => {
expect(1 + 1).toBe(2);
});
it("subtracts two numbers", () => {
expect(5 - 3).toBe(2);
});
});typescript
// math.test.ts
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
describe("数学运算", () => {
it("两数相加", () => {
expect(1 + 1).toBe(2);
});
it("两数相减", () => {
expect(5 - 3).toBe(2);
});
});6.2 Running Tests
6.2 运行测试
bash
undefinedbash
undefinedRun all tests
运行所有测试
bun test
bun test
Run specific file
运行特定文件
bun test math.test.ts
bun test math.test.ts
Run matching pattern
运行匹配模式的测试
bun test --grep "adds"
bun test --grep "adds"
Watch mode
监听模式
bun test --watch
bun test --watch
With coverage
生成覆盖率报告
bun test --coverage
bun test --coverage
Timeout
设置超时时间
bun test --timeout 5000
undefinedbun test --timeout 5000
undefined6.3 Matchers
6.3 匹配器
typescript
import { expect, test } from "bun:test";
test("matchers", () => {
// Equality
expect(1).toBe(1);
expect({ a: 1 }).toEqual({ a: 1 });
expect([1, 2]).toContain(1);
// Comparisons
expect(10).toBeGreaterThan(5);
expect(5).toBeLessThanOrEqual(5);
// Truthiness
expect(true).toBeTruthy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
// Strings
expect("hello").toMatch(/ell/);
expect("hello").toContain("ell");
// Arrays
expect([1, 2, 3]).toHaveLength(3);
// Exceptions
expect(() => {
throw new Error("fail");
}).toThrow("fail");
// Async
await expect(Promise.resolve(1)).resolves.toBe(1);
await expect(Promise.reject("err")).rejects.toBe("err");
});typescript
import { expect, test } from "bun:test";
test("匹配器", () => {
// 相等性
expect(1).toBe(1);
expect({ a: 1 }).toEqual({ a: 1 });
expect([1, 2]).toContain(1);
// 比较
expect(10).toBeGreaterThan(5);
expect(5).toBeLessThanOrEqual(5);
// 真值
expect(true).toBeTruthy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
// 字符串
expect("hello").toMatch(/ell/);
expect("hello").toContain("ell");
// 数组
expect([1, 2, 3]).toHaveLength(3);
// 异常
expect(() => {
throw new Error("fail");
}).toThrow("fail");
// 异步
await expect(Promise.resolve(1)).resolves.toBe(1);
await expect(Promise.reject("err")).rejects.toBe("err");
});6.4 Mocking
6.4 模拟
typescript
import { mock, spyOn } from "bun:test";
// Mock function
const mockFn = mock((x: number) => x * 2);
mockFn(5);
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith(5);
expect(mockFn.mock.results[0].value).toBe(10);
// Spy on method
const obj = {
method: () => "original",
};
const spy = spyOn(obj, "method").mockReturnValue("mocked");
expect(obj.method()).toBe("mocked");
expect(spy).toHaveBeenCalled();typescript
import { mock, spyOn } from "bun:test";
// 模拟函数
const mockFn = mock((x: number) => x * 2);
mockFn(5);
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith(5);
expect(mockFn.mock.results[0].value).toBe(10);
// 监听方法
const obj = {
method: () => "original",
};
const spy = spyOn(obj, "method").mockReturnValue("mocked");
expect(obj.method()).toBe("mocked");
expect(spy).toHaveBeenCalled();7. Bundling
7. 打包
7.1 Basic Build
7.1 基础构建
bash
undefinedbash
undefinedBundle for production
生产环境打包
bun build ./src/index.ts --outdir ./dist
bun build ./src/index.ts --outdir ./dist
With options
带选项打包
bun build ./src/index.ts
--outdir ./dist
--target browser
--minify
--sourcemap
--outdir ./dist
--target browser
--minify
--sourcemap
undefinedbun build ./src/index.ts
--outdir ./dist
--target browser
--minify
--sourcemap
--outdir ./dist
--target browser
--minify
--sourcemap
undefined7.2 Build API
7.2 构建API
typescript
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser", // or "bun", "node"
minify: true,
sourcemap: "external",
splitting: true,
format: "esm",
// External packages (not bundled)
external: ["react", "react-dom"],
// Define globals
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
},
// Naming
naming: {
entry: "[name].[hash].js",
chunk: "chunks/[name].[hash].js",
asset: "assets/[name].[hash][ext]",
},
});
if (!result.success) {
console.error(result.logs);
}typescript
const result = await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser", // 或 "bun", "node"
minify: true,
sourcemap: "external",
splitting: true,
format: "esm",
// 外部包(不打包)
external: ["react", "react-dom"],
// 定义全局变量
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
},
// 命名规则
naming: {
entry: "[name].[hash].js",
chunk: "chunks/[name].[hash].js",
asset: "assets/[name].[hash][ext]",
},
});
if (!result.success) {
console.error(result.logs);
}7.3 Compile to Executable
7.3 编译为可执行文件
bash
undefinedbash
undefinedCreate standalone executable
创建独立可执行文件
bun build ./src/cli.ts --compile --outfile myapp
bun build ./src/cli.ts --compile --outfile myapp
Cross-compile
跨平台编译
bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac
bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac
With embedded assets
嵌入资源
bun build ./src/cli.ts --compile --outfile myapp --embed ./assets
---bun build ./src/cli.ts --compile --outfile myapp --embed ./assets
---8. Migration from Node.js
8. 从Node.js迁移
8.1 Compatibility
8.1 兼容性
typescript
// Most Node.js APIs work out of the box
import fs from "fs";
import path from "path";
import crypto from "crypto";
// process is global
console.log(process.cwd());
console.log(process.env.HOME);
// Buffer is global
const buf = Buffer.from("hello");
// __dirname and __filename work
console.log(__dirname);
console.log(__filename);typescript
// 大多数Node.js API可直接使用
import fs from "fs";
import path from "path";
import crypto from "crypto";
// process是全局变量
console.log(process.cwd());
console.log(process.env.HOME);
// Buffer是全局变量
const buf = Buffer.from("hello");
// __dirname和__filename可用
console.log(__dirname);
console.log(__filename);8.2 Common Migration Steps
8.2 常见迁移步骤
bash
undefinedbash
undefined1. Install Bun
1. 安装Bun
curl -fsSL https://bun.sh/install | bash
curl -fsSL https://bun.sh/install | bash
2. Replace package manager
2. 替换包管理器
rm -rf node_modules package-lock.json
bun install
rm -rf node_modules package-lock.json
bun install
3. Update scripts in package.json
3. 更新package.json中的脚本
"start": "node index.js" → "start": "bun run index.ts"
"start": "node index.js" → "start": "bun run index.ts"
"test": "jest" → "test": "bun test"
"test": "jest" → "test": "bun test"
4. Add Bun types
4. 添加Bun类型定义
bun add -d @types/bun
undefinedbun add -d @types/bun
undefined8.3 Differences from Node.js
8.3 与Node.js的差异
typescript
// ❌ Node.js specific (may not work)
require("module") // Use import instead
require.resolve("pkg") // Use import.meta.resolve
__non_webpack_require__ // Not supported
// ✅ Bun equivalents
import pkg from "pkg";
const resolved = import.meta.resolve("pkg");
Bun.resolveSync("pkg", process.cwd());
// ❌ These globals differ
process.hrtime() // Use Bun.nanoseconds()
setImmediate() // Use queueMicrotask()
// ✅ Bun-specific features
const file = Bun.file("./data.txt"); // Fast file API
Bun.serve({ port: 3000, fetch: ... }); // Fast HTTP server
Bun.password.hash(password); // Built-in hashingtypescript
// ❌ Node.js特定API(可能无法工作)
require("module") // 使用import替代
require.resolve("pkg") // 使用import.meta.resolve
__non_webpack_require__ // 不支持
// ✅ Bun等效API
import pkg from "pkg";
const resolved = import.meta.resolve("pkg");
Bun.resolveSync("pkg", process.cwd());
// ❌ 这些全局变量存在差异
process.hrtime() // 使用Bun.nanoseconds()
setImmediate() // 使用queueMicrotask()
// ✅ Bun特有功能
const file = Bun.file("./data.txt"); // 快速文件API
Bun.serve({ port: 3000, fetch: ... }); // 快速HTTP服务器
Bun.password.hash(password); // 内置哈希功能9. Performance Tips
9. 性能优化技巧
9.1 Use Bun-native APIs
9.1 使用Bun原生API
typescript
// Slow (Node.js compat)
import fs from "fs/promises";
const content = await fs.readFile("./data.txt", "utf-8");
// Fast (Bun-native)
const file = Bun.file("./data.txt");
const content = await file.text();typescript
// 较慢(Node.js兼容模式)
import fs from "fs/promises";
const content = await fs.readFile("./data.txt", "utf-8");
// 较快(Bun原生)
const file = Bun.file("./data.txt");
const content = await file.text();9.2 Use Bun.serve for HTTP
9.2 使用Bun.serve搭建HTTP服务
typescript
// Don't: Express/Fastify (overhead)
import express from "express";
const app = express();
// Do: Bun.serve (native, 4-10x faster)
Bun.serve({
fetch(req) {
return new Response("Hello!");
},
});
// Or use Elysia (Bun-optimized framework)
import { Elysia } from "elysia";
new Elysia().get("/", () => "Hello!").listen(3000);typescript
// 不推荐:Express/Fastify(有性能开销)
import express from "express";
const app = express();
// 推荐:Bun.serve(原生实现,速度快4-10倍)
Bun.serve({
fetch(req) {
return new Response("Hello!");
},
});
// 或使用Elysia(针对Bun优化的框架)
import { Elysia } from "elysia";
new Elysia().get("/", () => "Hello!").listen(3000);9.3 Bundle for Production
9.3 生产环境打包
bash
undefinedbash
undefinedAlways bundle and minify for production
生产环境始终要打包并压缩
bun build ./src/index.ts --outdir ./dist --minify --target node
bun build ./src/index.ts --outdir ./dist --minify --target node
Then run the bundle
运行打包后的文件
bun run ./dist/index.js
---bun run ./dist/index.js
---Quick Reference
速查表
| Task | Command |
|---|---|
| Init project | |
| Install deps | |
| Add package | |
| Run script | |
| Run file | |
| Watch mode | |
| Run tests | |
| Build | |
| Execute pkg | |
| 任务 | 命令 |
|---|---|
| 初始化项目 | |
| 安装依赖 | |
| 添加包 | |
| 运行脚本 | |
| 运行文件 | |
| 监听模式 | |
| 运行测试 | |
| 构建项目 | |
| 执行包 | |