npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill bun深度知识:使用
mcp__documentation__fetch_docs并指定技术参数:bun以获取全面的文档。
# 安装 Bun
curl -fsSL https://bun.sh/install | bash
# 创建项目
bun init
# 直接运行 TypeScript(无需编译!)
bun run index.ts
# 使用监视模式运行
bun --watch run index.ts
# 安装依赖(比 npm/pnpm 更快)
bun install
# 添加包
bun add express zod
bun add -d typescript @types/node
# 移除包
bun remove package-name
# 更新包
bun update
# 运行脚本
bun run build
bun run dev
# 执行二进制文件
bunx prisma generate
// package.json
{
"workspaces": ["packages/*"]
}
# 安装所有工作区的依赖
bun install
# 在特定工作区运行
bun run --filter @myorg/api build
Deep Knowledge : Use
mcp__documentation__fetch_docswith technology:bunfor comprehensive documentation.
# Install Bun
curl -fsSL https://bun.sh/install | bash
# Create project
bun init
# Run TypeScript directly (no compilation needed!)
bun run index.ts
# Run with watch mode
bun --watch run index.ts
# Install dependencies (faster than npm/pnpm)
bun install
# Add packages
bun add express zod
bun add -d typescript @types/node
# Remove
bun remove package-name
# Update
bun update
# Run scripts
bun run build
bun run dev
# Execute binary
bunx prisma generate
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// 为生产环境构建
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'node', // 'browser' | 'bun'
minify: true,
sourcemap: 'external',
splitting: true, // 代码分割
format: 'esm', // 'cjs' | 'esm'
});
// 命令行界面
bun build ./src/index.ts --outdir ./dist --minify
// bunfig.toml 的替代方案 - build.ts
const result = await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
target: 'browser',
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
define: {
'process.env.NODE_ENV': '"production"',
},
external: ['react', 'react-dom'],
loader: {
'.png': 'file',
'.svg': 'text',
},
});
if (!result.success) {
console.error('构建失败:', result.logs);
process.exit(1);
}
// math.test.ts
import { describe, it, expect, beforeAll, mock } from 'bun:test';
describe('math', () => {
it('adds numbers', () => {
expect(1 + 2).toBe(3);
});
it('handles async', async () => {
const result = await fetchData();
expect(result).toBeDefined();
});
});
// 模拟
const mockFn = mock(() => 42);
mockFn();
expect(mockFn).toHaveBeenCalled();
// 模块模拟
mock.module('./config', () => ({
apiUrl: 'http://test.local',
}));
# 运行测试
bun test
# 监视模式
bun test --watch
# 覆盖率
bun test --coverage
# 过滤
bun test --filter "user"
// 原生 Bun 服务器(最快)
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/api/health') {
return Response.json({ status: 'ok' });
}
if (url.pathname === '/api/users' && req.method === 'POST') {
const body = await req.json();
return Response.json({ id: 1, ...body }, { status: 201 });
}
return new Response('Not Found', { status: 404 });
},
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
},
});
console.log('服务器运行在 http://localhost:3000');
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
const app = new Hono();
app.use('*', logger());
app.use('/api/*', cors());
app.get('/api/users', (c) => {
return c.json([{ id: 1, name: 'John' }]);
});
app.post('/api/users', async (c) => {
const body = await c.req.json();
return c.json({ id: 1, ...body }, 201);
});
export default app;
// 读取文件(返回字符串或 ArrayBuffer)
const text = await Bun.file('data.txt').text();
const json = await Bun.file('data.json').json();
const buffer = await Bun.file('image.png').arrayBuffer();
// 写入文件
await Bun.write('output.txt', 'Hello World');
await Bun.write('data.json', JSON.stringify(data));
// 流式处理大文件
const file = Bun.file('large.csv');
const stream = file.stream();
for await (const chunk of stream) {
process.stdout.write(chunk);
}
// 文件元数据
const file = Bun.file('data.txt');
console.log(file.size); // 字节数
console.log(file.type); // MIME 类型
import { Database } from 'bun:sqlite';
const db = new Database('app.db');
// 创建表
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('John', 'john@example.com');
const select = db.prepare('SELECT * FROM users WHERE id = ?');
const user = select.get(1);
// 查询所有
const all = db.prepare('SELECT * FROM users').all();
// 事务
db.transaction(() => {
insert.run('Alice', 'alice@example.com');
insert.run('Bob', 'bob@example.com');
})();
// .env 文件自动加载
const apiKey = Bun.env.API_KEY;
const port = Bun.env.PORT ?? '3000';
// process.env 同样有效
const nodeEnv = process.env.NODE_ENV;
import { $ } from 'bun';
// 简单命令
const result = await $`ls -la`;
console.log(result.stdout.toString());
// 使用变量(自动转义)
const filename = 'my file.txt';
await $`cat ${filename}`;
// 管道
const files = await $`ls`.text();
const count = await $`echo ${files} | wc -l`.text();
// 错误处理
try {
await $`exit 1`;
} catch (error) {
console.error('命令执行失败:', error.exitCode);
}
# bunfig.toml
[install]
# 注册表
registry = "https://registry.npmjs.org"
# CI 环境中的锁定文件冻结
frozenLockfile = true
[run]
# 脚本使用的 shell
shell = "bash"
[test]
# 测试配置
coverage = true
coverageDir = "coverage"
// 大多数 Node.js API 可用
import { readFile } from 'fs/promises';
import { createServer } from 'http';
import path from 'path';
// 一些差异
import.meta.dir; // __dirname 等效
import.meta.file; // __filename 等效
// 检查运行时
const isBun = typeof Bun !== 'undefined';
| 场景 | 应使用 |
|---|---|
| Node.js 运行时特定功能 | nodejs 技能 |
| Hono 框架 | 框架特定技能 |
| Elysia 框架 | 框架特定技能 |
| TypeScript 语法 | typescript 技能 |
| 测试策略 | testing-vitest 技能 |
| 反模式 | 为何不好 | 正确方法 |
|---|---|---|
| 使用 node_modules/.bin | 未针对 Bun 优化 | 改用 bunx |
| 忽略兼容性 | 某些 npm 包会失败 | 测试兼容性 |
| 在 Bun.serve 中使用复杂路由 | 难以维护 | 使用 Hono 或 Elysia |
| 未固定版本 | 破坏性变更 | 使用 bun.lockb |
| 混合使用包管理器 | 依赖不一致 | 坚持使用 bun |
| 不使用内置 SQLite | 额外依赖 | 使用 bun:sqlite |
| 阻塞操作 | 影响性能 | 使用异步 API |
| 不使用监视模式 | 开发循环慢 | 使用 --watch 标志 |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| "Module not found" | npm 兼容性问题 | 检查 Bun 兼容性列表 |
| "bun: command not found" | 未安装 | 安装 Bun 或添加到 PATH |
| 测试在 Bun 中失败但在 Jest 中通过 | 运行时不同 | 检查 Bun 特定 API |
| 安装缓慢 | 网络/缓存问题 | 使用 bun pm cache 清除缓存 |
| "Cannot find package" | 说明符错误 | 对 npm 包使用 npm: 前缀 |
| .ts 文件类型错误 | tsconfig 不匹配 | 检查 Bun 的默认配置 |
| 构建输出不正确 | 目标设置错误 | 在 Bun.build 中设置 target |
| SQLite 错误 | 数据库被锁定 | 正确关闭连接 |
| 任务 | Bun | Node.js |
|---|---|---|
| 安装依赖 | ~2s | ~15s |
| 运行 TS 文件 | <100ms | ~500ms (tsx) |
| HTTP 请求/秒 | ~100k | ~40k |
| 测试执行 | ~200ms | ~2s |
# Dockerfile
FROM oven/bun:1 AS base
WORKDIR /app
# 安装依赖
FROM base AS deps
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
# 构建
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN bun run build
# 生产环境
FROM base AS production
COPY --from=build /app/dist ./dist
COPY --from=build /app/package.json ./
USER bun
EXPOSE 3000
CMD ["bun", "run", "dist/index.js"]
深度知识:使用
mcp__documentation__fetch_docs并指定技术参数:bun以获取全面的文档。
每周安装次数
1
代码仓库
首次出现
3 天前
安全审计
安装于
amp1
cline1
openclaw1
opencode1
cursor1
kimi-cli1
// package.json
{
"workspaces": ["packages/*"]
}
# Install all workspace deps
bun install
# Run in specific workspace
bun run --filter @myorg/api build
// Build for production
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'node', // 'browser' | 'bun'
minify: true,
sourcemap: 'external',
splitting: true, // Code splitting
format: 'esm', // 'cjs' | 'esm'
});
// CLI
bun build ./src/index.ts --outdir ./dist --minify
// bunfig.toml alternative - build.ts
const result = await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
target: 'browser',
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
define: {
'process.env.NODE_ENV': '"production"',
},
external: ['react', 'react-dom'],
loader: {
'.png': 'file',
'.svg': 'text',
},
});
if (!result.success) {
console.error('Build failed:', result.logs);
process.exit(1);
}
// math.test.ts
import { describe, it, expect, beforeAll, mock } from 'bun:test';
describe('math', () => {
it('adds numbers', () => {
expect(1 + 2).toBe(3);
});
it('handles async', async () => {
const result = await fetchData();
expect(result).toBeDefined();
});
});
// Mocking
const mockFn = mock(() => 42);
mockFn();
expect(mockFn).toHaveBeenCalled();
// Module mocking
mock.module('./config', () => ({
apiUrl: 'http://test.local',
}));
# Run tests
bun test
# Watch mode
bun test --watch
# Coverage
bun test --coverage
# Filter
bun test --filter "user"
// Native Bun server (fastest)
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/api/health') {
return Response.json({ status: 'ok' });
}
if (url.pathname === '/api/users' && req.method === 'POST') {
const body = await req.json();
return Response.json({ id: 1, ...body }, { status: 201 });
}
return new Response('Not Found', { status: 404 });
},
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
},
});
console.log('Server running on http://localhost:3000');
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
const app = new Hono();
app.use('*', logger());
app.use('/api/*', cors());
app.get('/api/users', (c) => {
return c.json([{ id: 1, name: 'John' }]);
});
app.post('/api/users', async (c) => {
const body = await c.req.json();
return c.json({ id: 1, ...body }, 201);
});
export default app;
// Read file (returns string or ArrayBuffer)
const text = await Bun.file('data.txt').text();
const json = await Bun.file('data.json').json();
const buffer = await Bun.file('image.png').arrayBuffer();
// Write file
await Bun.write('output.txt', 'Hello World');
await Bun.write('data.json', JSON.stringify(data));
// Stream large files
const file = Bun.file('large.csv');
const stream = file.stream();
for await (const chunk of stream) {
process.stdout.write(chunk);
}
// File metadata
const file = Bun.file('data.txt');
console.log(file.size); // bytes
console.log(file.type); // MIME type
import { Database } from 'bun:sqlite';
const db = new Database('app.db');
// Create table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Prepared statements (recommended)
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
insert.run('John', 'john@example.com');
const select = db.prepare('SELECT * FROM users WHERE id = ?');
const user = select.get(1);
// Query all
const all = db.prepare('SELECT * FROM users').all();
// Transaction
db.transaction(() => {
insert.run('Alice', 'alice@example.com');
insert.run('Bob', 'bob@example.com');
})();
// .env file loaded automatically
const apiKey = Bun.env.API_KEY;
const port = Bun.env.PORT ?? '3000';
// process.env also works
const nodeEnv = process.env.NODE_ENV;
import { $ } from 'bun';
// Simple command
const result = await $`ls -la`;
console.log(result.stdout.toString());
// With variables (auto-escaped)
const filename = 'my file.txt';
await $`cat ${filename}`;
// Piping
const files = await $`ls`.text();
const count = await $`echo ${files} | wc -l`.text();
// Error handling
try {
await $`exit 1`;
} catch (error) {
console.error('Command failed:', error.exitCode);
}
# bunfig.toml
[install]
# Registry
registry = "https://registry.npmjs.org"
# Frozen lockfile in CI
frozenLockfile = true
[run]
# Shell for scripts
shell = "bash"
[test]
# Test configuration
coverage = true
coverageDir = "coverage"
// Most Node.js APIs work
import { readFile } from 'fs/promises';
import { createServer } from 'http';
import path from 'path';
// Some differences
import.meta.dir; // __dirname equivalent
import.meta.file; // __filename equivalent
// Check runtime
const isBun = typeof Bun !== 'undefined';
| Scenario | Use Instead |
|---|---|
| Node.js runtime specifics | nodejs skill |
| Hono framework | Framework-specific skill |
| Elysia framework | Framework-specific skill |
| TypeScript syntax | typescript skill |
| Testing strategies | testing-vitest skill |
| Anti-Pattern | Why It's Bad | Correct Approach |
|---|---|---|
| Using node_modules/.bin | Not optimized for Bun | Use bunx instead |
| Ignoring compatibility | Some npm packages fail | Test compatibility |
| Complex routing in Bun.serve | Hard to maintain | Use Hono or Elysia |
| Not pinning versions | Breaking changes | Use bun.lockb |
| Mixing package managers | Inconsistent deps | Stick to bun |
| Not using built-in SQLite | Extra dependency | Use bun:sqlite |
| Blocking operations | Defeats performance | Use async APIs |
| Not using watch mode | Slow dev loop | Use --watch flag |
| Issue | Cause | Solution |
|---|---|---|
| "Module not found" | npm compatibility issue | Check Bun compatibility list |
| "bun: command not found" | Not installed | Install Bun or add to PATH |
| Tests fail in Bun but not Jest | Different runtime | Check Bun-specific APIs |
| Slow install | Network/cache issue | Clear cache with bun pm cache |
| "Cannot find package" | Wrong specifier | Use npm: prefix for npm packages |
| Type errors with .ts files | tsconfig mismatch | Check Bun's default config |
| Build output incorrect | Wrong target | Set target in Bun.build |
| SQLite errors | Database locked | Close connections properly |
| Task | Bun | Node.js |
|---|---|---|
| Install deps | ~2s | ~15s |
| Run TS file | <100ms | ~500ms (tsx) |
| HTTP requests/sec | ~100k | ~40k |
| Test execution | ~200ms | ~2s |
# Dockerfile
FROM oven/bun:1 AS base
WORKDIR /app
# Install deps
FROM base AS deps
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
# Build
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN bun run build
# Production
FROM base AS production
COPY --from=build /app/dist ./dist
COPY --from=build /app/package.json ./
USER bun
EXPOSE 3000
CMD ["bun", "run", "dist/index.js"]
Deep Knowledge : Use
mcp__documentation__fetch_docswith technology:bunfor comprehensive documentation.
Weekly Installs
1
Repository
First Seen
3 days ago
Security Audits
Installed on
amp1
cline1
openclaw1
opencode1
cursor1
kimi-cli1
测试策略完整指南:单元/集成/E2E测试金字塔与自动化实践
11,200 周安装