Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun.
Add this skill
npx mdskills install sickn33/bun-developmentComprehensive reference guide covering Bun runtime APIs, package management, testing, and migration patterns with extensive code examples
1---2name: bun-development3description: "Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun."4---56# ⚡ Bun Development78> Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun).910## When to Use This Skill1112Use this skill when:1314- Starting new JS/TS projects with Bun15- Migrating from Node.js to Bun16- Optimizing development speed17- Using Bun's built-in tools (bundler, test runner)18- Troubleshooting Bun-specific issues1920---2122## 1. Getting Started2324### 1.1 Installation2526```bash27# macOS / Linux28curl -fsSL https://bun.sh/install | bash2930# Windows31powershell -c "irm bun.sh/install.ps1 | iex"3233# Homebrew34brew tap oven-sh/bun35brew install bun3637# npm (if needed)38npm install -g bun3940# Upgrade41bun upgrade42```4344### 1.2 Why Bun?4546| Feature | Bun | Node.js |47| :-------------- | :------------- | :-------------------------- |48| Startup time | ~25ms | ~100ms+ |49| Package install | 10-100x faster | Baseline |50| TypeScript | Native | Requires transpiler |51| JSX | Native | Requires transpiler |52| Test runner | Built-in | External (Jest, Vitest) |53| Bundler | Built-in | External (Webpack, esbuild) |5455---5657## 2. Project Setup5859### 2.1 Create New Project6061```bash62# Initialize project63bun init6465# Creates:66# ├── package.json67# ├── tsconfig.json68# ├── index.ts69# └── README.md7071# With specific template72bun create <template> <project-name>7374# Examples75bun create react my-app # React app76bun create next my-app # Next.js app77bun create vite my-app # Vite app78bun create elysia my-api # Elysia API79```8081### 2.2 package.json8283```json84{85 "name": "my-bun-project",86 "version": "1.0.0",87 "module": "index.ts",88 "type": "module",89 "scripts": {90 "dev": "bun run --watch index.ts",91 "start": "bun run index.ts",92 "test": "bun test",93 "build": "bun build ./index.ts --outdir ./dist",94 "lint": "bunx eslint ."95 },96 "devDependencies": {97 "@types/bun": "latest"98 },99 "peerDependencies": {100 "typescript": "^5.0.0"101 }102}103```104105### 2.3 tsconfig.json (Bun-optimized)106107```json108{109 "compilerOptions": {110 "lib": ["ESNext"],111 "module": "esnext",112 "target": "esnext",113 "moduleResolution": "bundler",114 "moduleDetection": "force",115 "allowImportingTsExtensions": true,116 "noEmit": true,117 "composite": true,118 "strict": true,119 "downlevelIteration": true,120 "skipLibCheck": true,121 "jsx": "react-jsx",122 "allowSyntheticDefaultImports": true,123 "forceConsistentCasingInFileNames": true,124 "allowJs": true,125 "types": ["bun-types"]126 }127}128```129130---131132## 3. Package Management133134### 3.1 Installing Packages135136```bash137# Install from package.json138bun install # or 'bun i'139140# Add dependencies141bun add express # Regular dependency142bun add -d typescript # Dev dependency143bun add -D @types/node # Dev dependency (alias)144bun add --optional pkg # Optional dependency145146# From specific registry147bun add lodash --registry https://registry.npmmirror.com148149# Install specific version150bun add react@18.2.0151bun add react@latest152bun add react@next153154# From git155bun add github:user/repo156bun add git+https://github.com/user/repo.git157```158159### 3.2 Removing & Updating160161```bash162# Remove package163bun remove lodash164165# Update packages166bun update # Update all167bun update lodash # Update specific168bun update --latest # Update to latest (ignore ranges)169170# Check outdated171bun outdated172```173174### 3.3 bunx (npx equivalent)175176```bash177# Execute package binaries178bunx prettier --write .179bunx tsc --init180bunx create-react-app my-app181182# With specific version183bunx -p typescript@4.9 tsc --version184185# Run without installing186bunx cowsay "Hello from Bun!"187```188189### 3.4 Lockfile190191```bash192# bun.lockb is a binary lockfile (faster parsing)193# To generate text lockfile for debugging:194bun install --yarn # Creates yarn.lock195196# Trust existing lockfile197bun install --frozen-lockfile198```199200---201202## 4. Running Code203204### 4.1 Basic Execution205206```bash207# Run TypeScript directly (no build step!)208bun run index.ts209210# Run JavaScript211bun run index.js212213# Run with arguments214bun run server.ts --port 3000215216# Run package.json script217bun run dev218bun run build219220# Short form (for scripts)221bun dev222bun build223```224225### 4.2 Watch Mode226227```bash228# Auto-restart on file changes229bun --watch run index.ts230231# With hot reloading232bun --hot run server.ts233```234235### 4.3 Environment Variables236237```typescript238// .env file is loaded automatically!239240// Access environment variables241const apiKey = Bun.env.API_KEY;242const port = Bun.env.PORT ?? "3000";243244// Or use process.env (Node.js compatible)245const dbUrl = process.env.DATABASE_URL;246```247248```bash249# Run with specific env file250bun --env-file=.env.production run index.ts251```252253---254255## 5. Built-in APIs256257### 5.1 File System (Bun.file)258259```typescript260// Read file261const file = Bun.file("./data.json");262const text = await file.text();263const json = await file.json();264const buffer = await file.arrayBuffer();265266// File info267console.log(file.size); // bytes268console.log(file.type); // MIME type269270// Write file271await Bun.write("./output.txt", "Hello, Bun!");272await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));273274// Stream large files275const reader = file.stream();276for await (const chunk of reader) {277 console.log(chunk);278}279```280281### 5.2 HTTP Server (Bun.serve)282283```typescript284const server = Bun.serve({285 port: 3000,286287 fetch(request) {288 const url = new URL(request.url);289290 if (url.pathname === "/") {291 return new Response("Hello World!");292 }293294 if (url.pathname === "/api/users") {295 return Response.json([296 { id: 1, name: "Alice" },297 { id: 2, name: "Bob" },298 ]);299 }300301 return new Response("Not Found", { status: 404 });302 },303304 error(error) {305 return new Response(`Error: ${error.message}`, { status: 500 });306 },307});308309console.log(`Server running at http://localhost:${server.port}`);310```311312### 5.3 WebSocket Server313314```typescript315const server = Bun.serve({316 port: 3000,317318 fetch(req, server) {319 // Upgrade to WebSocket320 if (server.upgrade(req)) {321 return; // Upgraded322 }323 return new Response("Upgrade failed", { status: 500 });324 },325326 websocket: {327 open(ws) {328 console.log("Client connected");329 ws.send("Welcome!");330 },331332 message(ws, message) {333 console.log(`Received: ${message}`);334 ws.send(`Echo: ${message}`);335 },336337 close(ws) {338 console.log("Client disconnected");339 },340 },341});342```343344### 5.4 SQLite (Bun.sql)345346```typescript347import { Database } from "bun:sqlite";348349const db = new Database("mydb.sqlite");350351// Create table352db.run(`353 CREATE TABLE IF NOT EXISTS users (354 id INTEGER PRIMARY KEY AUTOINCREMENT,355 name TEXT NOT NULL,356 email TEXT UNIQUE357 )358`);359360// Insert361const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");362insert.run("Alice", "alice@example.com");363364// Query365const query = db.prepare("SELECT * FROM users WHERE name = ?");366const user = query.get("Alice");367console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }368369// Query all370const allUsers = db.query("SELECT * FROM users").all();371```372373### 5.5 Password Hashing374375```typescript376// Hash password377const password = "super-secret";378const hash = await Bun.password.hash(password);379380// Verify password381const isValid = await Bun.password.verify(password, hash);382console.log(isValid); // true383384// With algorithm options385const bcryptHash = await Bun.password.hash(password, {386 algorithm: "bcrypt",387 cost: 12,388});389```390391---392393## 6. Testing394395### 6.1 Basic Tests396397```typescript398// math.test.ts399import { describe, it, expect, beforeAll, afterAll } from "bun:test";400401describe("Math operations", () => {402 it("adds two numbers", () => {403 expect(1 + 1).toBe(2);404 });405406 it("subtracts two numbers", () => {407 expect(5 - 3).toBe(2);408 });409});410```411412### 6.2 Running Tests413414```bash415# Run all tests416bun test417418# Run specific file419bun test math.test.ts420421# Run matching pattern422bun test --grep "adds"423424# Watch mode425bun test --watch426427# With coverage428bun test --coverage429430# Timeout431bun test --timeout 5000432```433434### 6.3 Matchers435436```typescript437import { expect, test } from "bun:test";438439test("matchers", () => {440 // Equality441 expect(1).toBe(1);442 expect({ a: 1 }).toEqual({ a: 1 });443 expect([1, 2]).toContain(1);444445 // Comparisons446 expect(10).toBeGreaterThan(5);447 expect(5).toBeLessThanOrEqual(5);448449 // Truthiness450 expect(true).toBeTruthy();451 expect(null).toBeNull();452 expect(undefined).toBeUndefined();453454 // Strings455 expect("hello").toMatch(/ell/);456 expect("hello").toContain("ell");457458 // Arrays459 expect([1, 2, 3]).toHaveLength(3);460461 // Exceptions462 expect(() => {463 throw new Error("fail");464 }).toThrow("fail");465466 // Async467 await expect(Promise.resolve(1)).resolves.toBe(1);468 await expect(Promise.reject("err")).rejects.toBe("err");469});470```471472### 6.4 Mocking473474```typescript475import { mock, spyOn } from "bun:test";476477// Mock function478const mockFn = mock((x: number) => x * 2);479mockFn(5);480expect(mockFn).toHaveBeenCalled();481expect(mockFn).toHaveBeenCalledWith(5);482expect(mockFn.mock.results[0].value).toBe(10);483484// Spy on method485const obj = {486 method: () => "original",487};488const spy = spyOn(obj, "method").mockReturnValue("mocked");489expect(obj.method()).toBe("mocked");490expect(spy).toHaveBeenCalled();491```492493---494495## 7. Bundling496497### 7.1 Basic Build498499```bash500# Bundle for production501bun build ./src/index.ts --outdir ./dist502503# With options504bun build ./src/index.ts \505 --outdir ./dist \506 --target browser \507 --minify \508 --sourcemap509```510511### 7.2 Build API512513```typescript514const result = await Bun.build({515 entrypoints: ["./src/index.ts"],516 outdir: "./dist",517 target: "browser", // or "bun", "node"518 minify: true,519 sourcemap: "external",520 splitting: true,521 format: "esm",522523 // External packages (not bundled)524 external: ["react", "react-dom"],525526 // Define globals527 define: {528 "process.env.NODE_ENV": JSON.stringify("production"),529 },530531 // Naming532 naming: {533 entry: "[name].[hash].js",534 chunk: "chunks/[name].[hash].js",535 asset: "assets/[name].[hash][ext]",536 },537});538539if (!result.success) {540 console.error(result.logs);541}542```543544### 7.3 Compile to Executable545546```bash547# Create standalone executable548bun build ./src/cli.ts --compile --outfile myapp549550# Cross-compile551bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux552bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac553554# With embedded assets555bun build ./src/cli.ts --compile --outfile myapp --embed ./assets556```557558---559560## 8. Migration from Node.js561562### 8.1 Compatibility563564```typescript565// Most Node.js APIs work out of the box566import fs from "fs";567import path from "path";568import crypto from "crypto";569570// process is global571console.log(process.cwd());572console.log(process.env.HOME);573574// Buffer is global575const buf = Buffer.from("hello");576577// __dirname and __filename work578console.log(__dirname);579console.log(__filename);580```581582### 8.2 Common Migration Steps583584```bash585# 1. Install Bun586curl -fsSL https://bun.sh/install | bash587588# 2. Replace package manager589rm -rf node_modules package-lock.json590bun install591592# 3. Update scripts in package.json593# "start": "node index.js" → "start": "bun run index.ts"594# "test": "jest" → "test": "bun test"595596# 4. Add Bun types597bun add -d @types/bun598```599600### 8.3 Differences from Node.js601602```typescript603// ❌ Node.js specific (may not work)604require("module") // Use import instead605require.resolve("pkg") // Use import.meta.resolve606__non_webpack_require__ // Not supported607608// ✅ Bun equivalents609import pkg from "pkg";610const resolved = import.meta.resolve("pkg");611Bun.resolveSync("pkg", process.cwd());612613// ❌ These globals differ614process.hrtime() // Use Bun.nanoseconds()615setImmediate() // Use queueMicrotask()616617// ✅ Bun-specific features618const file = Bun.file("./data.txt"); // Fast file API619Bun.serve({ port: 3000, fetch: ... }); // Fast HTTP server620Bun.password.hash(password); // Built-in hashing621```622623---624625## 9. Performance Tips626627### 9.1 Use Bun-native APIs628629```typescript630// Slow (Node.js compat)631import fs from "fs/promises";632const content = await fs.readFile("./data.txt", "utf-8");633634// Fast (Bun-native)635const file = Bun.file("./data.txt");636const content = await file.text();637```638639### 9.2 Use Bun.serve for HTTP640641```typescript642// Don't: Express/Fastify (overhead)643import express from "express";644const app = express();645646// Do: Bun.serve (native, 4-10x faster)647Bun.serve({648 fetch(req) {649 return new Response("Hello!");650 },651});652653// Or use Elysia (Bun-optimized framework)654import { Elysia } from "elysia";655new Elysia().get("/", () => "Hello!").listen(3000);656```657658### 9.3 Bundle for Production659660```bash661# Always bundle and minify for production662bun build ./src/index.ts --outdir ./dist --minify --target node663664# Then run the bundle665bun run ./dist/index.js666```667668---669670## Quick Reference671672| Task | Command |673| :----------- | :----------------------------------------- |674| Init project | `bun init` |675| Install deps | `bun install` |676| Add package | `bun add <pkg>` |677| Run script | `bun run <script>` |678| Run file | `bun run file.ts` |679| Watch mode | `bun --watch run file.ts` |680| Run tests | `bun test` |681| Build | `bun build ./src/index.ts --outdir ./dist` |682| Execute pkg | `bunx <pkg>` |683684---685686## Resources687688- [Bun Documentation](https://bun.sh/docs)689- [Bun GitHub](https://github.com/oven-sh/bun)690- [Elysia Framework](https://elysiajs.com/)691- [Bun Discord](https://bun.sh/discord)692
Full transparency — inspect the skill content before installing.