Bun JavaScript Runtime
Bun is an all-in-one JavaScript runtime, bundler, transpiler, and package manager, designed for extreme speed and a streamlined developer experience. It is built on Apple's WebKit engine's JavaScriptCore and written in Zig. As of version 1.3.12, Bun offers a highly performant alternative to Node.js, providing native support for TypeScript, JSX, and ES modules out of the box. The project maintains a rapid release cadence with frequent patch and minor versions, often weekly, addressing bugs and introducing new features. Its key differentiators include significantly faster startup times, execution speed, and comprehensive tooling built into a single executable, aiming to replace a multitude of separate tools like Node.js, npm/yarn/pnpm, webpack, Babel, and esbuild. Bun is currently stable for production use but continues to evolve rapidly, adding new features and improving compatibility.
Common errors
-
bun: command not found
cause Bun executable is not in the system's PATH.fixIf installed via `curl | bash`, the installer attempts to add Bun to your shell's PATH. Restart your terminal or source your shell configuration file (`~/.bashrc`, `~/.zshrc`). If installed via npm (`npm install -g bun`), ensure your npm global bin directory is in your PATH. On Windows, use `powershell -c "irm bun.sh/install.ps1|iex"` and restart PowerShell. -
Error: Cannot find module 'my-local-module' from '/path/to/file.ts'
cause Bun's module resolution differs or `tsconfig.json` paths are not correctly configured/interpreted.fixVerify that `my-local-module` is correctly declared in your `package.json` dependencies or that its path is correctly specified in `tsconfig.json`'s `paths` and `baseUrl`. Ensure file extensions are consistent (e.g., if it's a `.ts` file, use `.ts` or ensure your `tsconfig.json` allows omitting it). Use `bun install` to ensure all dependencies are resolved. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use CommonJS `require()` in an ES module (`.js` file with `"type": "module"` in `package.json` or a `.mjs` file) when Bun enforces ESM strictness.fixRefactor the code to use ES module `import` statements. If you explicitly need to `require` a CommonJS module from an ESM context, Bun (like Node.js) allows `createRequire` from `node:module`: `import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);` -
RangeError: Maximum call stack size exceeded (V8-specific error)
cause Bun (specifically its JavaScriptCore engine) might have a smaller default stack size or different tail call optimization behavior than V8 (Node.js). Deep recursion or large data structures can hit this limit sooner.fixRefactor recursive functions to be iterative where possible. For extremely deep recursion that cannot be easily converted, consider increasing the stack size if Bun provides a flag (check `bun --help`) or process large data in chunks to avoid deep stack usage.
Warnings
- breaking Bun's API and behavior, especially concerning Node.js compatibility, can change rapidly between minor versions. While efforts are made for backward compatibility, specific edge cases or less-common Node.js APIs might have different implementations or be temporarily unstable. Always review release notes for `bun upgrade`.
- gotcha Bun's package resolution and `bun install` behavior can differ from npm/yarn, particularly with symlinks, monorepos, and specific `postinstall` scripts. This can lead to packages not being found or unexpected build failures if not configured correctly.
- gotcha While Bun aims for high Node.js compatibility, certain Node.js APIs (e.g., specific `fs` options, `child_process` nuances, or older `stream` implementations) might behave differently or be partially implemented. Relying heavily on less common or deprecated Node.js features may lead to unexpected results.
- breaking The default module resolution strategy in Bun prefers `"exports"` field in `package.json` and supports various module extensions (`.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`). Differences in how Bun resolves files compared to Node.js (especially without `type: module` or with complex `tsconfig.json` paths) can cause 'Module not found' errors.
Install
-
npm install bun -
yarn add bun -
pnpm add bun
Imports
- Bun
import { Bun } from 'bun'/* Bun is a global object, no import needed */
- existsSync
import { existsSync } from 'fs';import { existsSync } from 'node:fs'; - Request
import { Request } from 'bun';const req = new Request('https://example.com');
Quickstart
import { Server, serve } from 'bun';
interface Env {
PORT?: string;
}
const env = process.env as Env;
const port = env.PORT ? parseInt(env.PORT, 10) : 3000;
const server = Bun.serve({
port: port,
fetch(request: Request): Response {
const url = new URL(request.url);
if (url.pathname === '/') {
return new Response('Hello from Bun! Visit /greet/:name');
}
if (url.pathname.startsWith('/greet/')) {
const name = url.pathname.split('/').pop();
return new Response(`Greetings, ${name}!`);
}
return new Response('404 Not Found', { status: 404 });
},
error(error: Error): Response {
console.error('Server error:', error);
return new Response('Internal Server Error', { status: 500 });
},
});
console.log(`Bun server listening on http://localhost:${server.port}`);