| | |

Bun 15 ⚡ Cheat Sheet

⏱️ Estimated read: 5 min | |

1. Installation & Upgrade

curl -fsSL https://bun.com/install | bash   # Install (macOS/Linux)
irm https://bun.com/install.ps1 | iex       # Install (Windows PowerShell)
npm install -g bun                          # Install via npm
brew install oven-sh/bun/bun                # Install via Homebrew
scoop install bun                           # Install via Scoop
bun upgrade                                 # Upgrade to latest stable
bun upgrade --canary                        # Upgrade to canary build
bun upgrade --stable                        # Return to stable from canary
bun --version                               # Check version
bun --revision                              # Check exact commit hash

2. Project Initialization

bun init                                    # Interactive init
bun init -y                                 # Accept defaults
bun init --react                            # React scaffold
bun init --react=tailwind                   # React + Tailwind
bun init --react=shadcn                     # React + shadcn/ui

3. Dependency Management

bun install                                 # Install all deps
bun add <pkg>                               # Add to dependencies
bun add -d <pkg>                            # Add to devDependencies
bun add --optional <pkg>                    # Add to optionalDependencies
bun add --exact <pkg>@<ver>                 # Pin exact version
bun add <pkg> --trust                       # Allow lifecycle scripts
bun add github:user/repo                    # Install from Git
bun remove <pkg>                            # Remove from all fields
bun remove -r <pkg>                         # Remove from all workspaces
bun update                                  # Update within ranges
bun update --latest                         # Update to latest
bun update -i                               # Interactive update

4. Lockfile & CI Installs

bun install --frozen-lockfile               # CI: fail if lockfile changes
bun ci                                      # Alias for frozen install
bun install --lockfile-only                 # Generate bun.lock only
bun install --no-save                       # Install without writing lockfile
bun install --save-text-lockfile --frozen-lockfile --lockfile-only
                                            # Migrate bun.lockb → bun.lock
bun pm hash                                 # Print lockfile hash for CI cache

5. Scripts & Binaries

bun run <script>                            # Run package.json script
bun <script>                                # Shorthand (scripts first)
bun run <file.ts>                           # Run file directly
bun --watch run <script>                    # Watch mode
bun --bun run <script>                      # Force Bun runtime for CLIs
bun run --filter '*' <script>               # Run in all workspaces
bun run --parallel <s1> <s2>                # Run concurrently
bunx <pkg>                                  # Run package without installing
bunx -p @angular/cli ng new my-app          # -p for package/binary mismatch
bunx --bun <bin>                            # Force Bun runtime
bunx --no-install <bin>                     # Skip install if not present

6. Running TypeScript & JSX

bun run index.ts                            # TypeScript
bun run App.tsx                             # TSX
bun run component.jsx                       # JSX
bun check                                   # Type check (tsc --noEmit)
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "types": ["bun"]
  }
}

7. Bun APIs (bun:sqlite, Bun.serve)

import { Database } from "bun:sqlite";
const db = new Database("app.sqlite", { safeIntegers: true });
db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
const q = db.query("SELECT * FROM users WHERE id = ?");
q.get(1); q.all(); q.iterate(); q.values();
const tx = db.transaction((a, b) => { /* queries */ });
const server = Bun.serve({
  port: 3000,
  fetch: () => new Response("Hello"),
  routes: {
    "/api/users/:id": (req) => Response.json({ id: req.params.id }),
    "/health": new Response("OK"),
  },
  websocket: {
    message(ws, msg) { ws.send(`Echo: ${msg}`); },
  },
  tls: { key: Bun.file("key.pem"), cert: Bun.file("cert.pem") },
});

8. File System (Bun.file, Bun.write)

const file = Bun.file("./data.json");       // lazy reference
file.size; file.type;                       // metadata without read
await file.text(); await file.json();       // read formats
await file.bytes(); await file.arrayBuffer();
for await (const chunk of file.stream()) {} // streaming
await Bun.write("./out.txt", "Hello");      // write
await Bun.write("./copy.txt", Bun.file("./src.txt"));
const writer = Bun.file("./log.txt").writer(); // incremental
writer.write("line\n"); await writer.end();
await file.delete();

9. Test Runner (bun:test)

import { test, expect, describe, beforeAll, afterAll, mock } from "bun:test";

describe("math", () => {
  test("addition", () => expect(1 + 1).toBe(2));
  test("async", async () => { await fetch("/api"); });
});
bun test                                    # Run all tests
bun test ./src/math.test.ts                 # Run specific file
bun test auth                               # Filter by path
bun test -t addition                        # Filter by name
bun test --watch                            # Rerun on change
bun test --bail                             # Stop after failures
bun test --coverage                         # Coverage report
bun test --update-snapshots                 # Regenerate snapshots

10. Bundling (bun build)

bun build ./index.tsx --outdir ./dist       # Browser bundle
bun build ./server.ts --target bun          # Bun target (// @bun pragma)
bun build ./cli.ts --target node --format cjs # Node CJS
bun build ./index.ts --production           # Minify + NODE_ENV
bun build ./index.ts --minify --keep-names  # Readable stack traces
bun build ./server.ts --bytecode            # Faster startup (Bun target)
bun build ./index.ts --drop=console         # Remove console calls
bun build --compile ./cli.ts --outfile ./mycli # Single executable
bun build ./a.ts ./b.ts --splitting         # Code splitting
bun build ./index.ts --external zod         # Exclude from bundle

11. CI/CD (GitHub Actions)

- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
  with:
    bun-version: latest
- run: bun install --frozen-lockfile
- run: bun test
- name: Get Bun cache
  id: bun-cache
  run: echo "dir=$(bun pm cache)" >> $GITHUB_OUTPUT
- uses: actions/cache@v4
  with:
    path: ${{ steps.bun-cache.outputs.dir }}
    key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}

12. Trusted Dependencies (Lifecycle Scripts)

{ "trustedDependencies": ["esbuild", "sharp"] }
bun install --ignore-scripts                # Skip all lifecycle scripts

13. Migration from Node.js / Express / Next.js

bun install                                 # Convert lockfile → bun.lock
bun add -d @types/bun                       # Bun type definitions
Node.js / npmBun
npm installbun install
npm install <pkg>bun add <pkg>
npm install -D <pkg>bun add -d <pkg>
npm uninstall <pkg>bun remove <pkg>
npm run <script>bun run <script>
node <file>bun <file>
npx <package>bunx <package>

14. Key Files

FilePurpose
package.jsonManifest (scripts, deps, trustedDependencies)
bun.lockText lockfile (v1.2+)
bun.lockbLegacy binary lockfile
bunfig.tomlBun configuration
tsconfig.jsonTypeScript config (read at runtime)
@types/bunBun API type definitions

15. Environment Variables

CI=true                                     # Detects CI environment
BUN_INSTALL="$HOME/.bun"                    # Install directory
PATH="$BUN_INSTALL/bin:$PATH"               # Add to PATH

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!