Use Cases

Bun:Claude Code 实战指南

了解bun:Claude Code 实战. 包含实用技巧和代码示例。

Bunランタイムの活用を通过 Claude Code 加速

BunはJavaScript/TypeScriptのオールインワンランタイムです。包マネージャー、バンドラー、测试ランナーを内蔵し、Node.jsの数倍の速度で動作します。Claude Codeを活用して、Bunの強力な機能を効率よく引入吧。

项目の立ち上げ

> Bunで新しいWeb应用项目创建。
> TypeScript、Hono框架、测试配置を含めて。
bun init my-app
cd my-app
bun add hono
// src/index.ts
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/health', (c) => {
  return c.json({ status: 'ok', runtime: 'bun' });
});

app.get('/api/users/:id', async (c) => {
  const id = c.req.param('id');
  const user = await getUser(id);
  return c.json(user);
});

export default {
  port: 3000,
  fetch: app.fetch,
};

BunのビルトインAPIを活用

> Bunの文件操作APIとSQLiteを使って、
> シンプルな数据ストア实现。
// src/db.ts
import { Database } from 'bun:sqlite';

const db = new Database('app.db', { create: true });

db.run(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

export const createUser = db.prepare(
  'INSERT INTO users (name, email) VALUES ($name, $email)'
);

export const getUser = db.prepare(
  'SELECT * FROM users WHERE id = $id'
);

// Bunの文件操作
export async function saveUpload(file: File) {
  const path = `./uploads/${file.name}`;
  await Bun.write(path, file);
  return path;
}

export async function readConfig() {
  const file = Bun.file('./config.json');
  return await file.json();
}

测试の実行

Bunには高速な测试ランナーが内蔵されています。

> API端点の测试を書いて。
> Bunの测试ランナーを使って。
// src/index.test.ts
import { describe, expect, it, beforeAll, afterAll } from 'bun:test';

describe('API endpoints', () => {
  it('GET /api/health returns ok', async () => {
    const res = await fetch('http://localhost:3000/api/health');
    const data = await res.json();
    expect(res.status).toBe(200);
    expect(data.status).toBe('ok');
  });

  it('GET /api/users/:id returns user', async () => {
    const res = await fetch('http://localhost:3000/api/users/1');
    expect(res.status).toBe(200);
    const user = await res.json();
    expect(user).toHaveProperty('name');
  });
});
# テスト実行
bun test

# ウォッチモード
bun test --watch

# カバレッジ
bun test --coverage

打包と构建

> 前端のコードをBunで打包して。
> Tree-shakingとminifyも有效にして。
// build.ts
await Bun.build({
  entrypoints: ['./src/client/index.tsx'],
  outdir: './dist',
  target: 'browser',
  minify: true,
  splitting: true,
  sourcemap: 'external',
  define: {
    'process.env.NODE_ENV': '"production"',
  },
});

console.log('Build complete!');

总结

Bunは那个圧倒的な速度と集成されたツールチェインで、开发体験を大幅に改善します。与 Claude Code組み合わせれば、Bun特有のAPIやパターンも快速習得可以。API开发指南测试戦略也可以参考。

Bun的详细信息请参阅Bun官方文档

#Claude Code #Bun #ランタイム #JavaScript #performance