xonecas.io
70160
Ce

cel-tui / files

cel-tui / .agents / skills / bun-development / SKILL.md

14.1 KB
1---
2name: bun-development
3description: "Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun)."
4risk: critical
5source: community
6date_added: "2026-02-27"
7---
8
9<!-- security-allowlist: curl-pipe-bash, irm-pipe-iex -->
10
11# ⚡ Bun Development
12
13> Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun).
14
15## When to Use This Skill
16
17Use this skill when:
18
19- Starting new JS/TS projects with Bun
20- Migrating from Node.js to Bun
21- Optimizing development speed
22- Using Bun's built-in tools (bundler, test runner)
23- Troubleshooting Bun-specific issues
24
25---
26
27## 1. Getting Started
28
29### 1.1 Installation
30
31```bash
32# macOS / Linux
33curl -fsSL https://bun.sh/install | bash
34
35# Windows
36powershell -c "irm bun.sh/install.ps1 | iex"
37
38# Homebrew
39brew tap oven-sh/bun
40brew install bun
41
42# npm (if needed)
43npm install -g bun
44
45# Upgrade
46bun upgrade
47```
48
49### 1.2 Why Bun?
50
51| Feature         | Bun            | Node.js                     |
52| :-------------- | :------------- | :-------------------------- |
53| Startup time    | ~25ms          | ~100ms+                     |
54| Package install | 10-100x faster | Baseline                    |
55| TypeScript      | Native         | Requires transpiler         |
56| JSX             | Native         | Requires transpiler         |
57| Test runner     | Built-in       | External (Jest, Vitest)     |
58| Bundler         | Built-in       | External (Webpack, esbuild) |
59
60---
61
62## 2. Project Setup
63
64### 2.1 Create New Project
65
66```bash
67# Initialize project
68bun init
69
70# Creates:
71# ├── package.json
72# ├── tsconfig.json
73# ├── index.ts
74# └── README.md
75
76# With specific template
77bun create <template> <project-name>
78
79# Examples
80bun create react my-app        # React app
81bun create next my-app         # Next.js app
82bun create vite my-app         # Vite app
83bun create elysia my-api       # Elysia API
84```
85
86### 2.2 package.json
87
88```json
89{
90  "name": "my-bun-project",
91  "version": "1.0.0",
92  "module": "index.ts",
93  "type": "module",
94  "scripts": {
95    "dev": "bun run --watch index.ts",
96    "start": "bun run index.ts",
97    "test": "bun test",
98    "build": "bun build ./index.ts --outdir ./dist",
99    "lint": "bunx eslint ."
100  },
101  "devDependencies": {
102    "@types/bun": "latest"
103  },
104  "peerDependencies": {
105    "typescript": "^5.0.0"
106  }
107}
108```
109
110### 2.3 tsconfig.json (Bun-optimized)
111
112```json
113{
114  "compilerOptions": {
115    "lib": ["ESNext"],
116    "module": "esnext",
117    "target": "esnext",
118    "moduleResolution": "bundler",
119    "moduleDetection": "force",
120    "allowImportingTsExtensions": true,
121    "noEmit": true,
122    "composite": true,
123    "strict": true,
124    "downlevelIteration": true,
125    "skipLibCheck": true,
126    "jsx": "react-jsx",
127    "allowSyntheticDefaultImports": true,
128    "forceConsistentCasingInFileNames": true,
129    "allowJs": true,
130    "types": ["bun-types"]
131  }
132}
133```
134
135---
136
137## 3. Package Management
138
139### 3.1 Installing Packages
140
141```bash
142# Install from package.json
143bun install              # or 'bun i'
144
145# Add dependencies
146bun add express          # Regular dependency
147bun add -d typescript    # Dev dependency
148bun add -D @types/node   # Dev dependency (alias)
149bun add --optional pkg   # Optional dependency
150
151# From specific registry
152bun add lodash --registry https://registry.npmmirror.com
153
154# Install specific version
155bun add react@18.2.0
156bun add react@latest
157bun add react@next
158
159# From git
160bun add github:user/repo
161bun add git+https://github.com/user/repo.git
162```
163
164### 3.2 Removing & Updating
165
166```bash
167# Remove package
168bun remove lodash
169
170# Update packages
171bun update              # Update all
172bun update lodash       # Update specific
173bun update --latest     # Update to latest (ignore ranges)
174
175# Check outdated
176bun outdated
177```
178
179### 3.3 bunx (npx equivalent)
180
181```bash
182# Execute package binaries
183bunx prettier --write .
184bunx tsc --init
185bunx create-react-app my-app
186
187# With specific version
188bunx -p typescript@4.9 tsc --version
189
190# Run without installing
191bunx cowsay "Hello from Bun!"
192```
193
194### 3.4 Lockfile
195
196```bash
197# bun.lockb is a binary lockfile (faster parsing)
198# To generate text lockfile for debugging:
199bun install --yarn    # Creates yarn.lock
200
201# Trust existing lockfile
202bun install --frozen-lockfile
203```
204
205---
206
207## 4. Running Code
208
209### 4.1 Basic Execution
210
211```bash
212# Run TypeScript directly (no build step!)
213bun run index.ts
214
215# Run JavaScript
216bun run index.js
217
218# Run with arguments
219bun run server.ts --port 3000
220
221# Run package.json script
222bun run dev
223bun run build
224
225# Short form (for scripts)
226bun dev
227bun build
228```
229
230### 4.2 Watch Mode
231
232```bash
233# Auto-restart on file changes
234bun --watch run index.ts
235
236# With hot reloading
237bun --hot run server.ts
238```
239
240### 4.3 Environment Variables
241
242```typescript
243// .env file is loaded automatically!
244
245// Access environment variables
246const apiKey = Bun.env.API_KEY;
247const port = Bun.env.PORT ?? "3000";
248
249// Or use process.env (Node.js compatible)
250const dbUrl = process.env.DATABASE_URL;
251```
252
253```bash
254# Run with specific env file
255bun --env-file=.env.production run index.ts
256```
257
258---
259
260## 5. Built-in APIs
261
262### 5.1 File System (Bun.file)
263
264```typescript
265// Read file
266const file = Bun.file("./data.json");
267const text = await file.text();
268const json = await file.json();
269const buffer = await file.arrayBuffer();
270
271// File info
272console.log(file.size); // bytes
273console.log(file.type); // MIME type
274
275// Write file
276await Bun.write("./output.txt", "Hello, Bun!");
277await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));
278
279// Stream large files
280const reader = file.stream();
281for await (const chunk of reader) {
282  console.log(chunk);
283}
284```
285
286### 5.2 HTTP Server (Bun.serve)
287
288```typescript
289const server = Bun.serve({
290  port: 3000,
291
292  fetch(request) {
293    const url = new URL(request.url);
294
295    if (url.pathname === "/") {
296      return new Response("Hello World!");
297    }
298
299    if (url.pathname === "/api/users") {
300      return Response.json([
301        { id: 1, name: "Alice" },
302        { id: 2, name: "Bob" },
303      ]);
304    }
305
306    return new Response("Not Found", { status: 404 });
307  },
308
309  error(error) {
310    return new Response(`Error: ${error.message}`, { status: 500 });
311  },
312});
313
314console.log(`Server running at http://localhost:${server.port}`);
315```
316
317### 5.3 WebSocket Server
318
319```typescript
320const server = Bun.serve({
321  port: 3000,
322
323  fetch(req, server) {
324    // Upgrade to WebSocket
325    if (server.upgrade(req)) {
326      return; // Upgraded
327    }
328    return new Response("Upgrade failed", { status: 500 });
329  },
330
331  websocket: {
332    open(ws) {
333      console.log("Client connected");
334      ws.send("Welcome!");
335    },
336
337    message(ws, message) {
338      console.log(`Received: ${message}`);
339      ws.send(`Echo: ${message}`);
340    },
341
342    close(ws) {
343      console.log("Client disconnected");
344    },
345  },
346});
347```
348
349### 5.4 SQLite (Bun.sql)
350
351```typescript
352import { Database } from "bun:sqlite";
353
354const db = new Database("mydb.sqlite");
355
356// Create table
357db.run(`
358  CREATE TABLE IF NOT EXISTS users (
359    id INTEGER PRIMARY KEY AUTOINCREMENT,
360    name TEXT NOT NULL,
361    email TEXT UNIQUE
362  )
363`);
364
365// Insert
366const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
367insert.run("Alice", "alice@example.com");
368
369// Query
370const query = db.prepare("SELECT * FROM users WHERE name = ?");
371const user = query.get("Alice");
372console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }
373
374// Query all
375const allUsers = db.query("SELECT * FROM users").all();
376```
377
378### 5.5 Password Hashing
379
380```typescript
381// Hash password
382const password = "super-secret";
383const hash = await Bun.password.hash(password);
384
385// Verify password
386const isValid = await Bun.password.verify(password, hash);
387console.log(isValid); // true
388
389// With algorithm options
390const bcryptHash = await Bun.password.hash(password, {
391  algorithm: "bcrypt",
392  cost: 12,
393});
394```
395
396---
397
398## 6. Testing
399
400### 6.1 Basic Tests
401
402```typescript
403// math.test.ts
404import { describe, it, expect, beforeAll, afterAll } from "bun:test";
405
406describe("Math operations", () => {
407  it("adds two numbers", () => {
408    expect(1 + 1).toBe(2);
409  });
410
411  it("subtracts two numbers", () => {
412    expect(5 - 3).toBe(2);
413  });
414});
415```
416
417### 6.2 Running Tests
418
419```bash
420# Run all tests
421bun test
422
423# Run specific file
424bun test math.test.ts
425
426# Run matching pattern
427bun test --grep "adds"
428
429# Watch mode
430bun test --watch
431
432# With coverage
433bun test --coverage
434
435# Timeout
436bun test --timeout 5000
437```
438
439### 6.3 Matchers
440
441```typescript
442import { expect, test } from "bun:test";
443
444test("matchers", () => {
445  // Equality
446  expect(1).toBe(1);
447  expect({ a: 1 }).toEqual({ a: 1 });
448  expect([1, 2]).toContain(1);
449
450  // Comparisons
451  expect(10).toBeGreaterThan(5);
452  expect(5).toBeLessThanOrEqual(5);
453
454  // Truthiness
455  expect(true).toBeTruthy();
456  expect(null).toBeNull();
457  expect(undefined).toBeUndefined();
458
459  // Strings
460  expect("hello").toMatch(/ell/);
461  expect("hello").toContain("ell");
462
463  // Arrays
464  expect([1, 2, 3]).toHaveLength(3);
465
466  // Exceptions
467  expect(() => {
468    throw new Error("fail");
469  }).toThrow("fail");
470
471  // Async
472  await expect(Promise.resolve(1)).resolves.toBe(1);
473  await expect(Promise.reject("err")).rejects.toBe("err");
474});
475```
476
477### 6.4 Mocking
478
479```typescript
480import { mock, spyOn } from "bun:test";
481
482// Mock function
483const mockFn = mock((x: number) => x * 2);
484mockFn(5);
485expect(mockFn).toHaveBeenCalled();
486expect(mockFn).toHaveBeenCalledWith(5);
487expect(mockFn.mock.results[0].value).toBe(10);
488
489// Spy on method
490const obj = {
491  method: () => "original",
492};
493const spy = spyOn(obj, "method").mockReturnValue("mocked");
494expect(obj.method()).toBe("mocked");
495expect(spy).toHaveBeenCalled();
496```
497
498---
499
500## 7. Bundling
501
502### 7.1 Basic Build
503
504```bash
505# Bundle for production
506bun build ./src/index.ts --outdir ./dist
507
508# With options
509bun build ./src/index.ts \
510  --outdir ./dist \
511  --target browser \
512  --minify \
513  --sourcemap
514```
515
516### 7.2 Build API
517
518```typescript
519const result = await Bun.build({
520  entrypoints: ["./src/index.ts"],
521  outdir: "./dist",
522  target: "browser", // or "bun", "node"
523  minify: true,
524  sourcemap: "external",
525  splitting: true,
526  format: "esm",
527
528  // External packages (not bundled)
529  external: ["react", "react-dom"],
530
531  // Define globals
532  define: {
533    "process.env.NODE_ENV": JSON.stringify("production"),
534  },
535
536  // Naming
537  naming: {
538    entry: "[name].[hash].js",
539    chunk: "chunks/[name].[hash].js",
540    asset: "assets/[name].[hash][ext]",
541  },
542});
543
544if (!result.success) {
545  console.error(result.logs);
546}
547```
548
549### 7.3 Compile to Executable
550
551```bash
552# Create standalone executable
553bun build ./src/cli.ts --compile --outfile myapp
554
555# Cross-compile
556bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
557bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac
558
559# With embedded assets
560bun build ./src/cli.ts --compile --outfile myapp --embed ./assets
561```
562
563---
564
565## 8. Migration from Node.js
566
567### 8.1 Compatibility
568
569```typescript
570// Most Node.js APIs work out of the box
571import fs from "fs";
572import path from "path";
573import crypto from "crypto";
574
575// process is global
576console.log(process.cwd());
577console.log(process.env.HOME);
578
579// Buffer is global
580const buf = Buffer.from("hello");
581
582// __dirname and __filename work
583console.log(__dirname);
584console.log(__filename);
585```
586
587### 8.2 Common Migration Steps
588
589```bash
590# 1. Install Bun
591curl -fsSL https://bun.sh/install | bash
592
593# 2. Replace package manager
594rm -rf node_modules package-lock.json
595bun install
596
597# 3. Update scripts in package.json
598# "start": "node index.js" → "start": "bun run index.ts"
599# "test": "jest" → "test": "bun test"
600
601# 4. Add Bun types
602bun add -d @types/bun
603```
604
605### 8.3 Differences from Node.js
606
607```typescript
608// ❌ Node.js specific (may not work)
609require("module")             // Use import instead
610require.resolve("pkg")        // Use import.meta.resolve
611__non_webpack_require__       // Not supported
612
613// ✅ Bun equivalents
614import pkg from "pkg";
615const resolved = import.meta.resolve("pkg");
616Bun.resolveSync("pkg", process.cwd());
617
618// ❌ These globals differ
619process.hrtime()              // Use Bun.nanoseconds()
620setImmediate()                // Use queueMicrotask()
621
622// ✅ Bun-specific features
623const file = Bun.file("./data.txt");  // Fast file API
624Bun.serve({ port: 3000, fetch: ... }); // Fast HTTP server
625Bun.password.hash(password);           // Built-in hashing
626```
627
628---
629
630## 9. Performance Tips
631
632### 9.1 Use Bun-native APIs
633
634```typescript
635// Slow (Node.js compat)
636import fs from "fs/promises";
637const content = await fs.readFile("./data.txt", "utf-8");
638
639// Fast (Bun-native)
640const file = Bun.file("./data.txt");
641const content = await file.text();
642```
643
644### 9.2 Use Bun.serve for HTTP
645
646```typescript
647// Don't: Express/Fastify (overhead)
648import express from "express";
649const app = express();
650
651// Do: Bun.serve (native, 4-10x faster)
652Bun.serve({
653  fetch(req) {
654    return new Response("Hello!");
655  },
656});
657
658// Or use Elysia (Bun-optimized framework)
659import { Elysia } from "elysia";
660new Elysia().get("/", () => "Hello!").listen(3000);
661```
662
663### 9.3 Bundle for Production
664
665```bash
666# Always bundle and minify for production
667bun build ./src/index.ts --outdir ./dist --minify --target node
668
669# Then run the bundle
670bun run ./dist/index.js
671```
672
673---
674
675## Quick Reference
676
677| Task         | Command                                    |
678| :----------- | :----------------------------------------- |
679| Init project | `bun init`                                 |
680| Install deps | `bun install`                              |
681| Add package  | `bun add <pkg>`                            |
682| Run script   | `bun run <script>`                         |
683| Run file     | `bun run file.ts`                          |
684| Watch mode   | `bun --watch run file.ts`                  |
685| Run tests    | `bun test`                                 |
686| Build        | `bun build ./src/index.ts --outdir ./dist` |
687| Execute pkg  | `bunx <pkg>`                               |
688
689---
690
691## Resources
692
693- [Bun Documentation](https://bun.sh/docs)
694- [Bun GitHub](https://github.com/oven-sh/bun)
695- [Elysia Framework](https://elysiajs.com/)
696- [Bun Discord](https://bun.sh/discord)
697
698## Limitations
699
700- Use this skill only when the task clearly matches the scope described above.
701- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
702- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.