Bun.js
All-in-one JavaScript/TypeScript toolkit: runtime, package manager, bundler, test runner.
Quick Reference
# Runtime
bun run index.ts # Execute file (TS/JSX native)
bun --watch index.ts # Watch mode
bun --hot index.ts # Hot reload
# Package Manager
bun install # Install deps (25x faster than npm)
bun add <pkg> # Add dependency
bun add -d <pkg> # Add dev dependency
bun remove <pkg> # Remove dependency
bun update # Update deps
bunx <pkg> # Execute package (like npx)
# Bundler
bun build ./src --outdir ./dist
bun build --minify --sourcemap linked
# Test Runner
bun test # Run tests
bun test --watch # Watch mode
bun test --coverage # With coverage
Runtime
Execution
bun run script.ts # Run file
bun run start # Run package.json script
bun --bun run start # Force Bun runtime (not Node)
Built-in APIs
// HTTP Server
Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello!");
},
});
// File I/O
const file = Bun.file("./data.json");
const text = await file.text();
await Bun.write("out.txt", "content");
// SQLite (native)
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
// Hashing
const hash = Bun.hash("data");
const password = await Bun.password.hash("secret");
// Shell
import { $ } from "bun";
await $`ls -la`;
Environment Variables
// Auto-loads .env files
const apiKey = Bun.env.API_KEY;
// or
const apiKey = process.env.API_KEY;
Package Manager
Commands
| Command | Description |
|---|---|
bun install | Install all deps |
bun add <pkg> | Add dependency |
bun add -d <pkg> | Add dev dependency |
bun add -g <pkg> | Add global |
bun remove <pkg> | Remove |
bun update | Update all |
bun outdated | Check outdated |
Lockfile
bun.lock- Text lockfile (v1.2+)bun.lockb- Binary lockfile (legacy)
CI/CD
bun ci # Frozen lockfile install
bun install --frozen-lockfile
Workspaces
{
"workspaces": ["packages/*"]
}
Bundler
Basic Usage
// JavaScript API
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser", // "browser" | "bun" | "node"
minify: true,
sourcemap: "linked",
});
# CLI
bun build ./src/index.ts --outdir ./dist --minify
Options
| Option | Description |
|---|---|
--target | browser, bun, node |
--format | esm, cjs, iife |
--minify | Enable minification |
--sourcemap | none, linked, inline, external |
--splitting | Code splitting |
--external | Exclude packages |
Standalone Executables
bun build ./cli.ts --compile --outfile mycli
./mycli
Test Runner
Writing Tests
import { test, expect, describe, beforeAll, mock } from "bun:test";
describe("math", () => {
test("adds numbers", () => {
expect(2 + 2).toBe(4);
});
test("async test", async () => {
const result = await fetchData();
expect(result).toBeDefined();
});
});
Mocking
import { mock, spyOn } from "bun:test";
const fn = mock(() => 42);
fn();
expect(fn).toHaveBeenCalled();
// Spy on object method
const spy = spyOn(console, "log");
CLI Options
bun test # Run all
bun test --watch # Watch mode
bun test --coverage # Coverage
bun test -t "pattern" # Filter by name
bun test --timeout 10000 # Set timeout
bun test --bail # Stop on first failure
bun test --update-snapshots # Update snapshots
Configuration (bunfig.toml)
# Runtime
preload = ["./setup.ts"]
logLevel = "debug"
[define]
"process.env.NODE_ENV" = "'production'"
# Package Manager
[install]
production = false
frozenLockfile = false
exact = false
[install.scopes]
myorg = { token = "$NPM_TOKEN", url = "https://registry.myorg.com/" }
# Test Runner
[test]
root = "./__tests__"
preload = ["./test-setup.ts"]
coverage = true
coverageThreshold = 0.8
Framework Integration
Next.js
bunx create-next-app my-app
cd my-app && bun dev
React
bun create react my-app
Express
import express from "express";
const app = express();
app.listen(3000);
TypeScript
Native support, no config needed. For types:
bun add -d @types/bun
Node.js Compatibility
Bun aims for Node.js compatibility. Most node:* modules work:
node:fs,node:path,node:http,node:crypto, etc.
Check compatibility status for specifics.
Documentation References
Core
- Welcome to Bun - Overview and getting started
- Installation - Install methods (npm, Homebrew, Docker)
- Quickstart - Build your first app
Runtime
- Runtime overview
- Bun APIs - Native APIs on Bun global
- bunfig.toml - Configuration file
- Environment Variables
- Module Resolution
- TypeScript | JSX
- Watch Mode - --watch and --hot
- Node.js Compatibility
- Globals | Web APIs
- Debugging - WebKit Inspector
Built-in Modules
HTTP & Networking
- HTTP Server | Routing | WebSockets
- TLS | Cookies | Fetch
- TCP | UDP | DNS
- HTMLRewriter | Transpiler
Package Manager
- install | add | remove | update | link
- publish | bunx | outdated | audit | why | patch
- Lockfile | Workspaces | Catalogs | Global cache
- Isolated installs | Lifecycle scripts | Scopes/registries
- Overrides | .npmrc | --filter
Bundler
- Overview | Loaders | Plugins | Executables
- CSS | HTML & static sites | Fullstack dev server
- Hot reloading | Macros | Minifier | Bytecode
- esbuild migration
Test Runner
- Overview | Writing tests | Mocks | Snapshots
- Lifecycle hooks | DOM testing | Code coverage
- Configuration | Finding tests | Dates/times | Reporters
Framework Guides
Database Guides
Deployment
- Docker | Vercel | Railway | Render
- AWS Lambda | Google Cloud Run | DigitalOcean
- PM2 | systemd
- GitHub Actions (runtime) | GitHub Actions (install)
Common Task Guides
- HTTP: Simple server | Common usage | fetch | File uploads | Streaming | Clustering | TLS | Hot reload
- Files: Read string | Read JSON | Write | Append | Copy | Delete | Exists | Watch | MIME type
- WebSockets: Simple | Pub/sub | Compression
- Process: Spawn | stdout/stderr | IPC | CLI args | CTRL+C | OS signals | Shell
- Utilities: Base64 | Hash password | UUID | Gzip | Sleep | Detect Bun | Version | Deep equals | Escape HTML
- Testing: Run tests | Watch mode | Mock functions | Mock clock | Snapshots | Coverage | happy-dom | Testing Library | Migrate from Jest
- Binary/Streams: Binary Data | ArrayBuffer | Blob | Buffer | Stream
Templates & Scaffolding
Project Links
- Roadmap | Contributing | Feedback | Blog