@@ -1,701 +0,0 @@
1----
2-name: bun-development
3-description: "Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun)."
4-risk: critical
5-source: community
6-date_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-
17-Use 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
33-curl -fsSL https://bun.sh/install | bash
34-
35-# Windows
36-powershell -c "irm bun.sh/install.ps1 | iex"
37-
38-# Homebrew
39-brew tap oven-sh/bun
40-brew install bun
41-
42-# npm (if needed)
43-npm install -g bun
44-
45-# Upgrade
46-bun 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
68-bun init
69-
70-# Creates:
71-# ├── package.json
72-# ├── tsconfig.json
73-# ├── index.ts
74-# └── README.md
75-
76-# With specific template
77-bun create <template> <project-name>
78-
79-# Examples
80-bun create react my-app # React app
81-bun create next my-app # Next.js app
82-bun create vite my-app # Vite app
83-bun 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
143-bun install # or 'bun i'
144-
145-# Add dependencies
146-bun add express # Regular dependency
147-bun add -d typescript # Dev dependency
148-bun add -D @types/node # Dev dependency (alias)
149-bun add --optional pkg # Optional dependency
150-
151-# From specific registry
152-bun add lodash --registry https://registry.npmmirror.com
153-
154-# Install specific version
155-bun add react@18.2.0
156-bun add react@latest
157-bun add react@next
158-
159-# From git
160-bun add github:user/repo
161-bun add git+https://github.com/user/repo.git
162-```
163-
164-### 3.2 Removing & Updating
165-
166-```bash
167-# Remove package
168-bun remove lodash
169-
170-# Update packages
171-bun update # Update all
172-bun update lodash # Update specific
173-bun update --latest # Update to latest (ignore ranges)
174-
175-# Check outdated
176-bun outdated
177-```
178-
179-### 3.3 bunx (npx equivalent)
180-
181-```bash
182-# Execute package binaries
183-bunx prettier --write .
184-bunx tsc --init
185-bunx create-react-app my-app
186-
187-# With specific version
188-bunx -p typescript@4.9 tsc --version
189-
190-# Run without installing
191-bunx 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:
199-bun install --yarn # Creates yarn.lock
200-
201-# Trust existing lockfile
202-bun 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!)
213-bun run index.ts
214-
215-# Run JavaScript
216-bun run index.js
217-
218-# Run with arguments
219-bun run server.ts --port 3000
220-
221-# Run package.json script
222-bun run dev
223-bun run build
224-
225-# Short form (for scripts)
226-bun dev
227-bun build
228-```
229-
230-### 4.2 Watch Mode
231-
232-```bash
233-# Auto-restart on file changes
234-bun --watch run index.ts
235-
236-# With hot reloading
237-bun --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
246-const apiKey = Bun.env.API_KEY;
247-const port = Bun.env.PORT ?? "3000";
248-
249-// Or use process.env (Node.js compatible)
250-const dbUrl = process.env.DATABASE_URL;
251-```
252-
253-```bash
254-# Run with specific env file
255-bun --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
266-const file = Bun.file("./data.json");
267-const text = await file.text();
268-const json = await file.json();
269-const buffer = await file.arrayBuffer();
270-
271-// File info
272-console.log(file.size); // bytes
273-console.log(file.type); // MIME type
274-
275-// Write file
276-await Bun.write("./output.txt", "Hello, Bun!");
277-await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));
278-
279-// Stream large files
280-const reader = file.stream();
281-for await (const chunk of reader) {
282- console.log(chunk);
283-}
284-```
285-
286-### 5.2 HTTP Server (Bun.serve)
287-
288-```typescript
289-const 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-
314-console.log(`Server running at http://localhost:${server.port}`);
315-```
316-
317-### 5.3 WebSocket Server
318-
319-```typescript
320-const 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
352-import { Database } from "bun:sqlite";
353-
354-const db = new Database("mydb.sqlite");
355-
356-// Create table
357-db.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
366-const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
367-insert.run("Alice", "alice@example.com");
368-
369-// Query
370-const query = db.prepare("SELECT * FROM users WHERE name = ?");
371-const user = query.get("Alice");
372-console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }
373-
374-// Query all
375-const allUsers = db.query("SELECT * FROM users").all();
376-```
377-
378-### 5.5 Password Hashing
379-
380-```typescript
381-// Hash password
382-const password = "super-secret";
383-const hash = await Bun.password.hash(password);
384-
385-// Verify password
386-const isValid = await Bun.password.verify(password, hash);
387-console.log(isValid); // true
388-
389-// With algorithm options
390-const 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
404-import { describe, it, expect, beforeAll, afterAll } from "bun:test";
405-
406-describe("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
421-bun test
422-
423-# Run specific file
424-bun test math.test.ts
425-
426-# Run matching pattern
427-bun test --grep "adds"
428-
429-# Watch mode
430-bun test --watch
431-
432-# With coverage
433-bun test --coverage
434-
435-# Timeout
436-bun test --timeout 5000
437-```
438-
439-### 6.3 Matchers
440-
441-```typescript
442-import { expect, test } from "bun:test";
443-
444-test("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
480-import { mock, spyOn } from "bun:test";
481-
482-// Mock function
483-const mockFn = mock((x: number) => x * 2);
484-mockFn(5);
485-expect(mockFn).toHaveBeenCalled();
486-expect(mockFn).toHaveBeenCalledWith(5);
487-expect(mockFn.mock.results[0].value).toBe(10);
488-
489-// Spy on method
490-const obj = {
491- method: () => "original",
492-};
493-const spy = spyOn(obj, "method").mockReturnValue("mocked");
494-expect(obj.method()).toBe("mocked");
495-expect(spy).toHaveBeenCalled();
496-```
497-
498----
499-
500-## 7. Bundling
501-
502-### 7.1 Basic Build
503-
504-```bash
505-# Bundle for production
506-bun build ./src/index.ts --outdir ./dist
507-
508-# With options
509-bun build ./src/index.ts \
510- --outdir ./dist \
511- --target browser \
512- --minify \
513- --sourcemap
514-```
515-
516-### 7.2 Build API
517-
518-```typescript
519-const 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-
544-if (!result.success) {
545- console.error(result.logs);
546-}
547-```
548-
549-### 7.3 Compile to Executable
550-
551-```bash
552-# Create standalone executable
553-bun build ./src/cli.ts --compile --outfile myapp
554-
555-# Cross-compile
556-bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
557-bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac
558-
559-# With embedded assets
560-bun 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
571-import fs from "fs";
572-import path from "path";
573-import crypto from "crypto";
574-
575-// process is global
576-console.log(process.cwd());
577-console.log(process.env.HOME);
578-
579-// Buffer is global
580-const buf = Buffer.from("hello");
581-
582-// __dirname and __filename work
583-console.log(__dirname);
584-console.log(__filename);
585-```
586-
587-### 8.2 Common Migration Steps
588-
589-```bash
590-# 1. Install Bun
591-curl -fsSL https://bun.sh/install | bash
592-
593-# 2. Replace package manager
594-rm -rf node_modules package-lock.json
595-bun 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
602-bun add -d @types/bun
603-```
604-
605-### 8.3 Differences from Node.js
606-
607-```typescript
608-// ❌ Node.js specific (may not work)
609-require("module") // Use import instead
610-require.resolve("pkg") // Use import.meta.resolve
611-__non_webpack_require__ // Not supported
612-
613-// ✅ Bun equivalents
614-import pkg from "pkg";
615-const resolved = import.meta.resolve("pkg");
616-Bun.resolveSync("pkg", process.cwd());
617-
618-// ❌ These globals differ
619-process.hrtime() // Use Bun.nanoseconds()
620-setImmediate() // Use queueMicrotask()
621-
622-// ✅ Bun-specific features
623-const file = Bun.file("./data.txt"); // Fast file API
624-Bun.serve({ port: 3000, fetch: ... }); // Fast HTTP server
625-Bun.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)
636-import fs from "fs/promises";
637-const content = await fs.readFile("./data.txt", "utf-8");
638-
639-// Fast (Bun-native)
640-const file = Bun.file("./data.txt");
641-const content = await file.text();
642-```
643-
644-### 9.2 Use Bun.serve for HTTP
645-
646-```typescript
647-// Don't: Express/Fastify (overhead)
648-import express from "express";
649-const app = express();
650-
651-// Do: Bun.serve (native, 4-10x faster)
652-Bun.serve({
653- fetch(req) {
654- return new Response("Hello!");
655- },
656-});
657-
658-// Or use Elysia (Bun-optimized framework)
659-import { Elysia } from "elysia";
660-new Elysia().get("/", () => "Hello!").listen(3000);
661-```
662-
663-### 9.3 Bundle for Production
664-
665-```bash
666-# Always bundle and minify for production
667-bun build ./src/index.ts --outdir ./dist --minify --target node
668-
669-# Then run the bundle
670-bun 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-- Use this skill only when the task clearly matches the scope described above.
700-- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
701-- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.