bun · diff

v1.0 to v1.0

153 added, 119 removed. Audit B to B.

---
name: Bun
- description: Use when building, testing, or deploying JavaScript/TypeScript applications. Reach for Bun when you need to run scripts, install packages, bundle code, or test applications — it's a drop-in replacement for Node.js with integrated package manager, test runner, and bundler.
+ description: Use when building, testing, and deploying JavaScript/TypeScript applications. Reach for Bun when you need to run scripts, manage dependencies, bundle code, or test applications with a single unified tool.
metadata:
+ provider: atomic
mintlify-proj: bun
version: "1.0"
internal: true
---
# Bun Skill Reference
## Product Summary
- Bun is an all-in-one JavaScript/TypeScript toolkit that replaces Node.js, npm, and bundlers with a single fast binary. It includes a runtime (powered by JavaScriptCore), package manager, test runner, and bundler. Key files: `bunfig.toml` (configuration), `package.json` (scripts and dependencies), `bun.lock` (lockfile). Primary CLI commands: `bun run`, `bun install`, `bun test`, `bun build`. See https://bun.com/docs for comprehensive documentation.
+ Bun is a unified JavaScript runtime, package manager, bundler, and test runner written in Zig. It replaces Node.js, npm, esbuild, and Jest with a single fast binary. Key files: `bunfig.toml` (configuration), `bun.lock` (lockfile), `package.json` (project metadata). Primary commands: `bun run`, `bun install`, `bun build`, `bun test`. Bun is 4x faster than Node.js on startup and 25x faster than npm for installations. Visit https://bun.com/docs for comprehensive documentation.
## When to Use
- - **Running scripts**: Execute `.js`, `.ts`, `.jsx`, `.tsx` files directly with `bun run` or `bun <file>` — no compilation step needed
- - **Package management**: Install dependencies with `bun install` (25x faster than npm) or add packages with `bun add`
- - **Testing**: Write and run Jest-compatible tests with `bun test` with TypeScript support built-in
- - **Bundling**: Bundle applications for browsers or servers with `bun build` or `Bun.build()` API
- - **HTTP servers**: Build servers with `Bun.serve()` API with native WebSocket and streaming support
- - **Monorepos**: Manage workspaces with `bun install --filter` and run scripts across packages
- - **Development**: Use watch mode (`--watch`) for live reloading during development
- - **Deployment**: Compile standalone executables with `bun build --compile` or deploy to Vercel, Railway, etc.
+ Use Bun when:
+ - **Running scripts**: Execute TypeScript/JavaScript files directly without compilation steps (`bun run file.ts`)
+ - **Managing dependencies**: Install, add, remove, or update packages faster than npm/yarn/pnpm (`bun install`, `bun add`)
+ - **Bundling code**: Build JavaScript/TypeScript for browser or server targets with `bun build`
+ - **Testing**: Run Jest-compatible tests with built-in test runner (`bun test`)
+ - **Building full-stack apps**: Bundle server and client code together into single executables
+ - **Monorepo workflows**: Use workspaces and filtering to manage multiple packages
+ - **Replacing Node.js**: Run any Node.js-compatible code with better performance
+ Do not use Bun for: type checking (use `tsc` separately), generating type declarations, or projects requiring exact Node.js compatibility for native modules.
+
## Quick Reference
### Essential Commands
- | Task | Command |
- | -------------------- | ---------------------------------------------------- |
- | Run a file | `bun run index.ts` or `bun index.ts` |
- | Run a script | `bun run dev` (from package.json) |
- | Install dependencies | `bun install` |
- | Add a package | `bun add react` or `bun add -d @types/node` |
- | Remove a package | `bun remove react` |
- | Run tests | `bun test` |
- | Watch tests | `bun test --watch` |
- | Build for browser | `bun build ./index.tsx --outdir ./dist` |
- | Build for server | `bun build ./index.tsx --outdir ./dist --target bun` |
- | Watch build | `bun build ./index.tsx --outdir ./dist --watch` |
- | Run with watch mode | `bun --watch run index.ts` |
- | Execute a package | `bunx cowsay "Hello"` |
-
- ### Configuration Files
+ | Task | Command | Notes |
+ | -------------------- | ------------------------------------------ | -------------------------------------------------- |
+ | Run TypeScript file | `bun run file.ts` | Transpiles on-the-fly; omit `run` for short form |
+ | Run package script | `bun run dev` | Executes script from `package.json` |
+ | Install dependencies | `bun install` | Creates `bun.lock` lockfile |
+ | Add package | `bun add react` | Adds to `dependencies`; use `-d` for dev |
+ | Remove package | `bun remove react` | Removes from `package.json` and `node_modules` |
+ | Run tests | `bun test` | Finds `*.test.ts`, `*.spec.ts` files automatically |
+ | Build bundle | `bun build ./src/index.ts --outdir ./dist` | Bundles with tree-shaking, minification optional |
+ | Watch mode | `bun --watch run file.ts` | Re-runs on file changes |
+ | Create project | `bun init` | Scaffolds new project with templates |
- | File | Purpose |
- | --------------- | ------------------------------------------------------------- |
- | `bunfig.toml` | Bun-specific configuration (optional, zero-config by default) |
- | `package.json` | Project metadata, scripts, dependencies |
- | `bun.lock` | Lockfile (text-based, replaces package-lock.json) |
- | `tsconfig.json` | TypeScript configuration (Bun respects this) |
+ ### Configuration File: bunfig.toml
- ### Key bunfig.toml Sections
+ Located at project root or `~/.bunfig.toml` (global). Optional but useful for customization.
```toml
[install]
- linker = "hoisted" # or "isolated" for strict dependency isolation
- dev = true # install devDependencies
- optional = true # install optionalDependencies
- peer = true # install peerDependencies
+ dev = true # Install devDependencies
+ optional = true # Install optionalDependencies
+ peer = true # Install peerDependencies
+ linker = "hoisted" # "hoisted" or "isolated" (pnpm-style)
+ saveTextLockfile = true # Use text bun.lock instead of binary
+ [serve]
+ port = 3000 # Default port for Bun.serve()
+
[test]
- root = "."
- coverage = false
- coverageThreshold = 0.9
+ root = "." # Test root directory
+ coverage = false # Enable coverage reporting
+ timeout = 5000 # Per-test timeout in ms
+ preload = ["./setup.ts"] # Scripts to run before tests
[run]
- shell = "system" # or "bun" for Bun's shell
- bun = true # alias node to bun in scripts
+ shell = "system" # "system" or "bun" (Windows defaults to "bun")
+ bun = true # Auto-alias node to bun in scripts
```
- ### File Type Support
+ ### File Types Supported
- Bun natively transpiles and executes:
- - `.js`, `.jsx` — JavaScript and JSX
- - `.ts`, `.tsx` — TypeScript and TSX
- - `.json`, `.jsonc`, `.toml`, `.yaml` — Data files (parsed at build time)
- - `.html` — HTML with asset bundling
- - `.css` — CSS bundling
+ Bun natively handles: `.js`, `.jsx`, `.ts`, `.tsx`, `.json`, `.jsonc`, `.toml`, `.yaml`, `.html`, `.css`, `.wasm`, `.node`. No configuration needed—just import and use.
+ ### Key Bun APIs
+
+ | API | Purpose | Example |
+ | ---------------- | ----------------- | ------------------------------------------- |
+ | `Bun.serve()` | Start HTTP server | `Bun.serve({ port: 3000, fetch: handler })` |
+ | `Bun.file()` | Read/write files | `await Bun.file("path.txt").text()` |
+ | `Bun.write()` | Write to disk | `await Bun.write("out.txt", data)` |
+ | `Bun.build()` | Bundle code | `await Bun.build({ entrypoints, outdir })` |
+ | `Bun.Transpiler` | Transpile code | `new Bun.Transpiler({ loader: "tsx" })` |
+ | `Bun.spawn()` | Run child process | `Bun.spawn(["ls", "-la"])` |
+
## Decision Guidance
- | Scenario | Use | Why |
- | ------------------------ | ------------------------------------------------------- | --------------------------------------------------------------------------- |
- | **Package installation** | `bun install` vs `npm install` | Bun is 25x faster, uses global cache, supports workspaces |
- | **Linker strategy** | `--linker isolated` vs `--linker hoisted` | Isolated prevents phantom dependencies; hoisted is traditional npm behavior |
- | **Build target** | `--target browser` vs `--target bun` vs `--target node` | Browser for web apps, bun for server code, node for Node.js compatibility |
- | **Module format** | `--format esm` vs `--format cjs` | ESM is default; use CJS for CommonJS compatibility |
- | **Watch mode** | `--watch` vs manual restart | Use `--watch` for development; Bun uses OS-native file watchers (fast) |
- | **Test execution** | `--concurrent` vs sequential | Concurrent for independent tests; sequential for tests with shared state |
- | **Bundling** | `bun build` vs `Bun.build()` API | CLI for simple builds; API for programmatic control and in-memory bundling |
+ ### When to Use Hoisted vs Isolated Linker
+ | Scenario | Use | Reason |
+ | ----------------------------- | ---------- | ------------------------------------------------- |
+ | New monorepo/workspaces | `isolated` | Prevents phantom dependencies, stricter isolation |
+ | New single-package project | `hoisted` | Traditional npm behavior, simpler |
+ | Existing project (pre-v1.3.2) | `hoisted` | Backward compatibility |
+ | Migrating from pnpm | `isolated` | Matches pnpm's approach |
+
+ Set in `bunfig.toml`: `linker = "isolated"` or via CLI: `bun install --linker isolated`
+
+ ### When to Use bun build vs bun run
+
+ | Use Case | Tool | Why |
+ | --------------------------- | ------------------------- | ------------------------------------ |
+ | Execute TypeScript directly | `bun run` | Fast transpilation, no output files |
+ | Prepare for production | `bun build` | Minification, tree-shaking, bundling |
+ | Ship single executable | `bun build --compile` | Creates standalone binary |
+ | Development server | `bun run` + `Bun.serve()` | Hot reload, fast iteration |
+
+ ### When to Use --concurrent in Tests
+
+ | Scenario | Use `--concurrent` | Reason |
+ | ----------------------- | ------------------ | --------------------------------------------- |
+ | Independent async tests | Yes | Parallel execution speeds up suite |
+ | Tests with shared state | No | Use `test.serial()` for order-dependent tests |
+ | Database/API tests | Maybe | Only if tests don't interfere |
+ | Unit tests | Yes | Usually safe and faster |
+
## Workflow
### 1. Initialize a Project
```bash
bun init my-app
cd my-app
```
- Choose template: Blank, React, or Library. Creates `package.json`, `tsconfig.json`, `bunfig.toml`.
+ Choose template: Blank, React, or Library. Creates `package.json`, `tsconfig.json`, `.gitignore`.
### 2. Install Dependencies
```bash
bun install
- # or add specific packages
- bun add react
- bun add -d @types/node typescript
```
- Generates `bun.lock` lockfile. Use `--frozen-lockfile` in CI for reproducible builds.
+ Reads `package.json`, downloads packages, creates `bun.lock`. Much faster than npm.
- ### 3. Write Code
- Create `.ts`, `.tsx`, `.js`, or `.jsx` files. Bun transpiles on the fly.
+ ### 3. Add Packages
+ ```bash
+ bun add react
+ bun add -d @types/react typescript
+ ```
+ Updates `package.json` and `bun.lock` automatically.
- ### 4. Run Code
+ ### 4. Write and Run Code
```bash
+ # Create index.ts
+ echo "console.log('Hello Bun!')" > index.ts
+
+ # Run it
bun run index.ts
- # or with watch mode
- bun --watch run index.ts
```
+ Bun transpiles TypeScript on-the-fly; no build step needed.
- ### 5. Add Scripts to package.json
- ```json
- {
- "scripts": {
- "dev": "bun --watch run src/index.ts",
- "build": "bun build ./src/index.tsx --outdir ./dist",
- "test": "bun test",
- "start": "bun run dist/index.js"
- }
- }
+ ### 5. Create HTTP Server
+ ```typescript
+ // server.ts
+ const server = Bun.serve({
+ port: 3000,
+ fetch(req) {
+ return new Response("Hello!");
+ },
+ });
+ console.log(`Listening on ${server.url}`);
```
-
- ### 6. Run Scripts
```bash
- bun run dev
- bun run build
- bun run test
+ bun run server.ts
```
- ### 7. Test
+ ### 6. Write Tests
+ ```typescript
+ // math.test.ts
+ import { test, expect } from "bun:test";
+
+ test("2 + 2 = 4", () => {
+ expect(2 + 2).toBe(4);
+ });
+ ```
```bash
- # Write tests in *.test.ts or *.spec.ts
bun test
- bun test --watch
- bun test --coverage
```
+ Finds and runs all `*.test.ts` files automatically.
- ### 8. Bundle for Production
+ ### 7. Bundle for Production
```bash
- bun build ./src/index.tsx --outdir ./dist --minify
- # or for a server
- bun build ./src/server.ts --outdir ./dist --target bun --minify
+ bun build ./src/index.ts --outdir ./dist --minify
```
+ Outputs optimized bundle to `dist/`. Use `--target browser|node|bun` to control output format.
- ### 9. Deploy
- Commit `bun.lock` to version control. In CI, use `bun ci` (equivalent to `bun install --frozen-lockfile`).
+ ### 8. Create Standalone Executable
+ ```bash
+ bun build ./cli.ts --outfile mycli --compile
+ ./mycli
+ ```
+ Bundles code + Bun runtime into single executable; no dependencies needed.
## Common Gotchas
- - **Watch mode flag placement**: Use `bun --watch run dev`, not `bun run dev --watch`. Flags after the script name are passed to the script itself.
- - **Lifecycle scripts**: Bun does not execute `postinstall` scripts for security. Add packages to `trustedDependencies` in `package.json` to allow them.
- - **Node.js compatibility**: Bun aims for Node.js compatibility but is not 100% complete. Check `/runtime/nodejs-compat` for current status.
- - **TypeScript errors in Bun global**: Install `@types/bun` and configure `tsconfig.json` with `"lib": ["ESNext"]` and `"module": "Preserve"`.
- - **Module resolution**: Bun supports both ESM and CommonJS. Use `import` for ESM (recommended) or `require()` for CommonJS.
- - **Bundler is not a type checker**: Use `tsc` separately for type checking and `.d.ts` generation; `bun build` only transpiles.
- - **Auto-install disabled in production**: Set `install.auto = "disable"` in `bunfig.toml` for production environments.
- - **Phantom dependencies**: Use `--linker isolated` to prevent accidental imports of transitive dependencies.
- - **Environment variables**: Bun auto-loads `.env`, `.env.local`, `.env.[NODE_ENV]`. Disable with `env = false` in `bunfig.toml`.
- - **Minification by default for bun target**: When `target: "bun"`, identifiers are minified by default; use `minify: false` to disable.
+ - **Lifecycle scripts disabled by default**: Bun doesn't run `postinstall` scripts for security. Add trusted packages to `trustedDependencies` in `package.json` to allow them.
+ - **`bun run` vs `bun <script>`**: If a built-in Bun command exists with the same name, use `bun run <script>` explicitly to run package.json scripts.
+ - **Watch mode flag placement**: Use `bun --watch run file.ts`, not `bun run file.ts --watch`. Flags after the filename are passed to the script itself.
+ - **TypeScript errors on Bun global**: Install `@types/bun` and add `"lib": ["ESNext"]` to `tsconfig.json` compilerOptions.
+ - **Lockfile format**: Bun v1.2+ uses text `bun.lock` by default (not binary `bun.lockb`). Commit to version control.
+ - **Auto-install disabled in CI**: Set `install.auto = "disable"` in `bunfig.toml` for production to prevent unexpected package downloads.
+ - **Node.js compatibility**: Bun implements most Node.js APIs but not all. Check docs for `node:` module support before relying on Node-specific code.
+ - **Bundler always bundles**: Unlike esbuild, `bun build` always bundles by default. Use `Bun.Transpiler` to transpile individual files without bundling.
+ - **No type checking in bundler**: `bun build` does not type-check. Run `tsc --noEmit` separately for type validation.
+ - **Peer dependencies installed by default**: Unlike npm, Bun installs peer dependencies automatically. Set `peer = false` in `bunfig.toml` to disable.
## Verification Checklist
Before submitting work with Bun:
- - [ ] Run `bun install` to ensure dependencies are locked
- - [ ] Run `bun test` to verify all tests pass
- - [ ] Run `bun run build` (or your build script) and verify output in `dist/` or configured `outdir`
- - [ ] Test the built output: `bun run dist/index.js` or `node dist/index.js` (if targeting Node.js)
- - [ ] Check `bun.lock` is committed to version control
- - [ ] Verify `bunfig.toml` has correct configuration for your environment (dev vs. production)
- - [ ] Run `bun run --filter <pattern> <script>` in monorepos to test workspace scripts
- - [ ] For HTTP servers, test with `curl` or browser: `curl http://localhost:3000`
- - [ ] For bundled apps, check bundle size: `ls -lh dist/`
- - [ ] Verify no console errors or warnings in test output
- - [ ] If using TypeScript, ensure `tsconfig.json` is properly configured
+ - [ ] Run `bun install` to verify dependencies resolve without errors
+ - [ ] Run `bun run <script>` to test main entry point
+ - [ ] Run `bun test` and verify all tests pass
+ - [ ] Run `bun build` and check output files exist in `outdir`
+ - [ ] Verify `bun.lock` is committed to version control (not `.gitignore`d)
+ - [ ] Check `bunfig.toml` for any environment-specific settings that should be removed
+ - [ ] Confirm no `node_modules` folder is committed (should be in `.gitignore`)
+ - [ ] Test with `--production` flag if building for deployment: `bun install --production`
+ - [ ] Verify TypeScript files have no type errors: `bun run tsc --noEmit` (if tsc installed)
+ - [ ] Check that `package.json` `"type": "module"` is set for ESM projects
## Resources
- - **Comprehensive navigation**: https://bun.com/docs/llms.txt — Full page-by-page listing for agent navigation
- - **Runtime documentation**: https://bun.com/docs/runtime — Execute files, scripts, and use Bun APIs
- - **Package manager**: https://bun.com/docs/pm/cli/install — Install, add, remove, and manage dependencies
- - **Test runner**: https://bun.com/docs/test — Write and run Jest-compatible tests
- - **Bundler**: https://bun.com/docs/bundler — Bundle for browsers and servers
+ **Comprehensive navigation**: https://bun.com/docs/llms.txt — Page-by-page listing of all Bun documentation.
+
+ **Critical pages**:
+ 1. [Bun Runtime](https://bun.com/docs/runtime) — Execute files, scripts, and manage the runtime
+ 2. [Package Manager](https://bun.com/docs/pm/cli/install) — Install, add, remove packages and manage dependencies
+ 3. [Bundler](https://bun.com/docs/bundler) — Bundle JavaScript/TypeScript for production
+ 4. [Test Runner](https://bun.com/docs/test) — Write and run Jest-compatible tests
+ 5. [bunfig.toml](https://bun.com/docs/runtime/bunfig) — Configure Bun's behavior
---
> For additional documentation and navigation, see: https://bun.com/docs/llms.txt