+
+Official documentation for Bun: the fast, all-in-one JavaScript runtime.
+
+## Development
+
+Install the [Mintlify CLI](https://www.npmjs.com/package/mint) to preview the documentation locally:
+
+```bash
+bun install -g mint
+```
+
+Run the development server:
+
+```bash
+mint dev
+```
+
+The site will be available at `http://localhost:3000`.
+
+## Contributing
+
+Contributions are welcome! Please open an issue or submit a pull request.
diff --git a/docs/api/file.md b/docs/api/file.md
deleted file mode 100644
index 16e5359017..0000000000
--- a/docs/api/file.md
+++ /dev/null
@@ -1,19 +0,0 @@
-Bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
-
-`Bun.file(path)` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) that represents a lazily-loaded file.
-
-When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call:
-
-```js
-const blob = Bun.file("input.txt");
-await Bun.write("output.txt", blob);
-```
-
-On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)).
-
-`Bun.write` also supports [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. It automatically converts to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
-
-```js
-// Eventually, this will stream the response to disk but today it buffers
-await Bun.write("index.html", await fetch("https://example.com"));
-```
diff --git a/docs/api/globals.md b/docs/api/globals.md
deleted file mode 100644
index 1a98bb0899..0000000000
--- a/docs/api/globals.md
+++ /dev/null
@@ -1,387 +0,0 @@
-Bun implements the following globals.
-
-{% table %}
-
-- Global
-- Source
-- Notes
-
----
-
-- [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
-- Web
--
-
----
-
-- [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
-- Web
--
-
----
-
-- [`alert`](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
-- Web
-- Intended for command-line tools
-
----
-
-- [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
-- Web
--
-
----
-
-- [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)
-- Node.js
-- See [Node.js > `Buffer`](https://bun.com/docs/runtime/nodejs-apis#node-buffer)
-
----
-
-- `Bun`
-- Bun
-- Subject to change as additional APIs are added
-
----
-
-- [`ByteLengthQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy)
-- Web
--
-
----
-
-- [`confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
-- Web
-- Intended for command-line tools
-
----
-
-- [`__dirname`](https://nodejs.org/api/globals.html#__dirname)
-- Node.js
--
-
----
-
-- [`__filename`](https://nodejs.org/api/globals.html#__filename)
-- Node.js
--
-
----
-
-- [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob)
-- Web
--
-
----
-
-- [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa)
-- Web
--
-
----
-
-- `BuildMessage`
-- Bun
--
-
----
-
-- [`clearImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearImmediate)
-- Web
--
-
----
-
-- [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval)
-- Web
--
-
----
-
-- [`clearTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout)
-- Web
--
-
----
-
-- [`console`](https://developer.mozilla.org/en-US/docs/Web/API/console)
-- Web
--
-
----
-
-- [`CountQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy)
-- Web
--
-
----
-
-- [`Crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto)
-- Web
--
-
----
-
-- [`crypto`](https://developer.mozilla.org/en-US/docs/Web/API/crypto)
-- Web
--
-
----
-
-- [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey)
-- Web
--
-
----
-
-- [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent)
-- Web
--
-
----
-
-- [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event)
-- Web
-- Also [`ErrorEvent`](https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent) [`CloseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent).
-
----
-
-- [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)
-- Web
--
-
----
-
-- [`exports`](https://nodejs.org/api/globals.html#exports)
-- Node.js
--
-
----
-
-- [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch)
-- Web
--
-
----
-
-- [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
-- Web
--
-
----
-
-- [`global`](https://nodejs.org/api/globals.html#global)
-- Node.js
-- See [Node.js > `global`](https://bun.com/docs/runtime/nodejs-apis#global).
-
----
-
-- [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis)
-- Cross-platform
-- Aliases to `global`
-
----
-
-- [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
-- Web
--
-
----
-
-- [`HTMLRewriter`](https://bun.com/docs/api/html-rewriter)
-- Cloudflare
--
-
----
-
-- [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON)
-- Web
--
-
----
-
-- [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent)
-- Web
--
-
----
-
-- [`module`](https://nodejs.org/api/globals.html#module)
-- Node.js
--
-
----
-
-- [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/performance)
-- Web
--
-
----
-
-- [`process`](https://nodejs.org/api/process.html)
-- Node.js
-- See [Node.js > `process`](https://bun.com/docs/runtime/nodejs-apis#node-process)
-
----
-
-- [`prompt`](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)
-- Web
-- Intended for command-line tools
-
----
-
-- [`queueMicrotask()`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask)
-- Web
--
-
----
-
-- [`ReadableByteStreamController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController)
-- Web
--
-
----
-
-- [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
-- Web
--
-
----
-
-- [`ReadableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController)
-- Web
--
-
----
-
-- [`ReadableStreamDefaultReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader)
-- Web
--
-
----
-
-- [`reportError`](https://developer.mozilla.org/en-US/docs/Web/API/reportError)
-- Web
--
-
----
-
-- [`require()`](https://nodejs.org/api/globals.html#require)
-- Node.js
--
-
----
-
-- `ResolveMessage`
-- Bun
--
-
----
-
-- [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
-- Web
--
-
----
-
-- [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
-- Web
--
-
----
-
-- [`setImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate)
-- Web
--
-
----
-
-- [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval)
-- Web
--
-
----
-
-- [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout)
-- Web
--
-
----
-
-- [`ShadowRealm`](https://github.com/tc39/proposal-shadowrealm)
-- Web
-- Stage 3 proposal
-
----
-
-- [`SubtleCrypto`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto)
-- Web
--
-
----
-
-- [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException)
-- Web
--
-
----
-
-- [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder)
-- Web
--
-
----
-
-- [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder)
-- Web
--
-
----
-
-- [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream)
-- Web
--
-
----
-
-- [`TransformStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStreamDefaultController)
-- Web
--
-
----
-
-- [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL)
-- Web
--
-
----
-
-- [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
-- Web
--
-
----
-
-- [`WebAssembly`](https://nodejs.org/api/globals.html#webassembly)
-- Web
--
-
----
-
-- [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)
-- Web
--
-
----
-
-- [`WritableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultController)
-- Web
--
-
----
-
-- [`WritableStreamDefaultWriter`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter)
-- Web
--
-
-{% /table %}
diff --git a/docs/api/http.md b/docs/api/http.md
deleted file mode 100644
index 201e911cfe..0000000000
--- a/docs/api/http.md
+++ /dev/null
@@ -1,1408 +0,0 @@
-The page primarily documents the Bun-native `Bun.serve` API. Bun also implements [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and the Node.js [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html) modules.
-
-{% callout %}
-These modules have been re-implemented to use Bun's fast internal HTTP infrastructure. Feel free to use these modules directly; frameworks like [Express](https://expressjs.com/) that depend on these modules should work out of the box. For granular compatibility information, see [Runtime > Node.js APIs](https://bun.com/docs/runtime/nodejs-apis).
-{% /callout %}
-
-To start a high-performance HTTP server with a clean API, the recommended approach is [`Bun.serve`](#start-a-server-bun-serve).
-
-## `Bun.serve()`
-
-Use `Bun.serve` to start an HTTP server in Bun.
-
-```ts
-Bun.serve({
- // `routes` requires Bun v1.2.3+
- routes: {
- // Static routes
- "/api/status": new Response("OK"),
-
- // Dynamic routes
- "/users/:id": req => {
- return new Response(`Hello User ${req.params.id}!`);
- },
-
- // Per-HTTP method handlers
- "/api/posts": {
- GET: () => new Response("List posts"),
- POST: async req => {
- const body = await req.json();
- return Response.json({ created: true, ...body });
- },
- },
-
- // Wildcard route for all routes that start with "/api/" and aren't otherwise matched
- "/api/*": Response.json({ message: "Not found" }, { status: 404 }),
-
- // Redirect from /blog/hello to /blog/hello/world
- "/blog/hello": Response.redirect("/blog/hello/world"),
-
- // Serve a file by buffering it in memory
- "/favicon.ico": new Response(await Bun.file("./favicon.ico").bytes(), {
- headers: {
- "Content-Type": "image/x-icon",
- },
- }),
- },
-
- // (optional) fallback for unmatched routes:
- // Required if Bun's version < 1.2.3
- fetch(req) {
- return new Response("Not Found", { status: 404 });
- },
-});
-```
-
-### Routing
-
-Routes in `Bun.serve()` receive a `BunRequest` (which extends [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)) and return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) or `Promise`. This makes it easier to use the same code for both sending & receiving HTTP requests.
-
-```ts
-// Simplified for brevity
-interface BunRequest extends Request {
- params: Record;
- readonly cookies: CookieMap;
-}
-```
-
-#### Async/await in routes
-
-You can use async/await in route handlers to return a `Promise`.
-
-```ts
-import { sql, serve } from "bun";
-
-serve({
- port: 3001,
- routes: {
- "/api/version": async () => {
- const [version] = await sql`SELECT version()`;
- return Response.json(version);
- },
- },
-});
-```
-
-#### Promise in routes
-
-You can also return a `Promise` from a route handler.
-
-```ts
-import { sql, serve } from "bun";
-
-serve({
- routes: {
- "/api/version": () => {
- return new Promise(resolve => {
- setTimeout(async () => {
- const [version] = await sql`SELECT version()`;
- resolve(Response.json(version));
- }, 100);
- });
- },
- },
-});
-```
-
-#### Type-safe route parameters
-
-TypeScript parses route parameters when passed as a string literal, so that your editor will show autocomplete when accessing `request.params`.
-
-```ts
-import type { BunRequest } from "bun";
-
-Bun.serve({
- routes: {
- // TypeScript knows the shape of params when passed as a string literal
- "/orgs/:orgId/repos/:repoId": req => {
- const { orgId, repoId } = req.params;
- return Response.json({ orgId, repoId });
- },
-
- "/orgs/:orgId/repos/:repoId/settings": (
- // optional: you can explicitly pass a type to BunRequest:
- req: BunRequest<"/orgs/:orgId/repos/:repoId/settings">,
- ) => {
- const { orgId, repoId } = req.params;
- return Response.json({ orgId, repoId });
- },
- },
-});
-```
-
-Percent-encoded route parameter values are automatically decoded. Unicode characters are supported. Invalid unicode is replaced with the unicode replacement character `&0xFFFD;`.
-
-### Static responses
-
-Routes can also be `Response` objects (without the handler function). Bun.serve() optimizes it for zero-allocation dispatch - perfect for health checks, redirects, and fixed content:
-
-```ts
-Bun.serve({
- routes: {
- // Health checks
- "/health": new Response("OK"),
- "/ready": new Response("Ready", {
- headers: {
- // Pass custom headers
- "X-Ready": "1",
- },
- }),
-
- // Redirects
- "/blog": Response.redirect("https://bun.com/blog"),
-
- // API responses
- "/api/config": Response.json({
- version: "1.0.0",
- env: "production",
- }),
- },
-});
-```
-
-Static responses do not allocate additional memory after initialization. You can generally expect at least a 15% performance improvement over manually returning a `Response` object.
-
-Static route responses are cached for the lifetime of the server object. To reload static routes, call `server.reload(options)`.
-
-### File Responses vs Static Responses
-
-When serving files in routes, there are two distinct behaviors depending on whether you buffer the file content or serve it directly:
-
-```ts
-Bun.serve({
- routes: {
- // Static route - content is buffered in memory at startup
- "/logo.png": new Response(await Bun.file("./logo.png").bytes()),
-
- // File route - content is read from filesystem on each request
- "/download.zip": new Response(Bun.file("./download.zip")),
- },
-});
-```
-
-**Static routes** (`new Response(await file.bytes())`) buffer content in memory at startup:
-
-- **Zero filesystem I/O** during requests - content served entirely from memory
-- **ETag support** - Automatically generates and validates ETags for caching
-- **If-None-Match** - Returns `304 Not Modified` when client ETag matches
-- **No 404 handling** - Missing files cause startup errors, not runtime 404s
-- **Memory usage** - Full file content stored in RAM
-- **Best for**: Small static assets, API responses, frequently accessed files
-
-**File routes** (`new Response(Bun.file(path))`) read from filesystem per request:
-
-- **Filesystem reads** on each request - checks file existence and reads content
-- **Built-in 404 handling** - Returns `404 Not Found` if file doesn't exist or becomes inaccessible
-- **Last-Modified support** - Uses file modification time for `If-Modified-Since` headers
-- **If-Modified-Since** - Returns `304 Not Modified` when file hasn't changed since client's cached version
-- **Range request support** - Automatically handles partial content requests with `Content-Range` headers
-- **Streaming transfers** - Uses buffered reader with backpressure handling for efficient memory usage
-- **Memory efficient** - Only buffers small chunks during transfer, not entire file
-- **Best for**: Large files, dynamic content, user uploads, files that change frequently
-
-### HTTP Caching Behavior
-
-Both route types implement HTTP caching standards but with different strategies:
-
-#### Static Routes Caching
-
-- **ETag generation**: Automatically computes ETag hash from content at startup
-- **If-None-Match**: Validates client ETag against server ETag
-- **304 responses**: Returns `304 Not Modified` with empty body when ETags match
-- **Cache headers**: Inherits any `Cache-Control` headers you provide in the Response
-- **Consistency**: ETag remains constant until server restart or route reload
-
-#### File Routes Caching
-
-- **Last-Modified**: Uses file's `mtime` for `Last-Modified` header
-- **If-Modified-Since**: Compares client date with file modification time
-- **304 responses**: Returns `304 Not Modified` when file unchanged since client's cached version
-- **Content-Length**: Automatically set based on current file size
-- **Dynamic validation**: Checks file modification time on each request
-
-#### Status Code Handling
-
-Both route types automatically adjust status codes:
-
-- **200 → 204**: Empty files (0 bytes) return `204 No Content` instead of `200 OK`
-- **200 → 304**: Successful cache validation returns `304 Not Modified`
-- **File routes only**: Missing or inaccessible files return `404 Not Found`
-
-```ts
-const server = Bun.serve({
- static: {
- "/api/time": new Response(new Date().toISOString()),
- },
-
- fetch(req) {
- return new Response("404!");
- },
-});
-
-// Update the time every second.
-setInterval(() => {
- server.reload({
- static: {
- "/api/time": new Response(new Date().toISOString()),
- },
-
- fetch(req) {
- return new Response("404!");
- },
- });
-}, 1000);
-```
-
-Reloading routes only impact the next request. In-flight requests continue to use the old routes. After in-flight requests to old routes are finished, the old routes are freed from memory.
-
-To simplify error handling, static routes do not support streaming response bodies from `ReadableStream` or an `AsyncIterator`. Fortunately, you can still buffer the response in memory first:
-
-```ts
-const time = await fetch("https://api.example.com/v1/data");
-// Buffer the response in memory first.
-const blob = await time.blob();
-
-const server = Bun.serve({
- static: {
- "/api/data": new Response(blob),
- },
-
- fetch(req) {
- return new Response("404!");
- },
-});
-```
-
-### Route precedence
-
-Routes are matched in order of specificity:
-
-1. Exact routes (`/users/all`)
-2. Parameter routes (`/users/:id`)
-3. Wildcard routes (`/users/*`)
-4. Global catch-all (`/*`)
-
-```ts
-Bun.serve({
- routes: {
- // Most specific first
- "/api/users/me": () => new Response("Current user"),
- "/api/users/:id": req => new Response(`User ${req.params.id}`),
- "/api/*": () => new Response("API catch-all"),
- "/*": () => new Response("Global catch-all"),
- },
-});
-```
-
-### Per-HTTP Method Routes
-
-Route handlers can be specialized by HTTP method:
-
-```ts
-Bun.serve({
- routes: {
- "/api/posts": {
- // Different handlers per method
- GET: () => new Response("List posts"),
- POST: async req => {
- const post = await req.json();
- return Response.json({ id: crypto.randomUUID(), ...post });
- },
- PUT: async req => {
- const updates = await req.json();
- return Response.json({ updated: true, ...updates });
- },
- DELETE: () => new Response(null, { status: 204 }),
- },
- },
-});
-```
-
-You can pass any of the following methods:
-
-| Method | Usecase example |
-| --------- | ------------------------------- |
-| `GET` | Fetch a resource |
-| `HEAD` | Check if a resource exists |
-| `OPTIONS` | Get allowed HTTP methods (CORS) |
-| `DELETE` | Delete a resource |
-| `PATCH` | Update a resource |
-| `POST` | Create a resource |
-| `PUT` | Update a resource |
-
-When passing a function instead of an object, all methods will be handled by that function:
-
-```ts
-const server = Bun.serve({
- routes: {
- "/api/version": () => Response.json({ version: "1.0.0" }),
- },
-});
-
-await fetch(new URL("/api/version", server.url));
-await fetch(new URL("/api/version", server.url), { method: "PUT" });
-// ... etc
-```
-
-### Hot Route Reloading
-
-Update routes without server restarts using `server.reload()`:
-
-```ts
-const server = Bun.serve({
- routes: {
- "/api/version": () => Response.json({ version: "1.0.0" }),
- },
-});
-
-// Deploy new routes without downtime
-server.reload({
- routes: {
- "/api/version": () => Response.json({ version: "2.0.0" }),
- },
-});
-```
-
-### Error Handling
-
-Bun provides structured error handling for routes:
-
-```ts
-Bun.serve({
- routes: {
- // Errors are caught automatically
- "/api/risky": () => {
- throw new Error("Something went wrong");
- },
- },
- // Global error handler
- error(error) {
- console.error(error);
- return new Response(`Internal Error: ${error.message}`, {
- status: 500,
- headers: {
- "Content-Type": "text/plain",
- },
- });
- },
-});
-```
-
-### HTML imports
-
-Bun supports importing HTML files directly into your server code, enabling full-stack applications with both server-side and client-side code. HTML imports work in two modes:
-
-**Development (`bun --hot`):** Assets are bundled on-demand at runtime, enabling hot module replacement (HMR) for a fast, iterative development experience. When you change your frontend code, the browser automatically updates without a full page reload.
-
-**Production (`bun build`):** When building with `bun build --target=bun`, the `import index from "./index.html"` statement resolves to a pre-built manifest object containing all bundled client assets. `Bun.serve` consumes this manifest to serve optimized assets with zero runtime bundling overhead. This is ideal for deploying to production.
-
-```ts
-import myReactSinglePageApp from "./index.html";
-
-Bun.serve({
- routes: {
- "/": myReactSinglePageApp,
- },
-});
-```
-
-HTML imports don't just serve HTML — it's a full-featured frontend bundler, transpiler, and toolkit built using Bun's [bundler](https://bun.com/docs/bundler), JavaScript transpiler and CSS parser. You can use this to build full-featured frontends with React, TypeScript, Tailwind CSS, and more.
-
-For a complete guide on building full-stack applications with HTML imports, including detailed examples and best practices, see [/docs/bundler/fullstack](https://bun.com/docs/bundler/fullstack).
-
-### Practical example: REST API
-
-Here's a basic database-backed REST API using Bun's router with zero dependencies:
-
-{% codetabs %}
-
-```ts#server.ts
-import type { Post } from "./types.ts";
-import { Database } from "bun:sqlite";
-
-const db = new Database("posts.db");
-db.exec(`
- CREATE TABLE IF NOT EXISTS posts (
- id TEXT PRIMARY KEY,
- title TEXT NOT NULL,
- content TEXT NOT NULL,
- created_at TEXT NOT NULL
- )
-`);
-
-Bun.serve({
- routes: {
- // List posts
- "/api/posts": {
- GET: () => {
- const posts = db.query("SELECT * FROM posts").all();
- return Response.json(posts);
- },
-
- // Create post
- POST: async req => {
- const post: Omit = await req.json();
- const id = crypto.randomUUID();
-
- db.query(
- `INSERT INTO posts (id, title, content, created_at)
- VALUES (?, ?, ?, ?)`,
- ).run(id, post.title, post.content, new Date().toISOString());
-
- return Response.json({ id, ...post }, { status: 201 });
- },
- },
-
- // Get post by ID
- "/api/posts/:id": req => {
- const post = db
- .query("SELECT * FROM posts WHERE id = ?")
- .get(req.params.id);
-
- if (!post) {
- return new Response("Not Found", { status: 404 });
- }
-
- return Response.json(post);
- },
- },
-
- error(error) {
- console.error(error);
- return new Response("Internal Server Error", { status: 500 });
- },
-});
-```
-
-```ts#types.ts
-export interface Post {
- id: string;
- title: string;
- content: string;
- created_at: string;
-}
-```
-
-{% /codetabs %}
-
-### Routing performance
-
-`Bun.serve()`'s router builds on top uWebSocket's [tree-based approach](https://github.com/oven-sh/bun/blob/0d1a00fa0f7830f8ecd99c027fce8096c9d459b6/packages/bun-uws/src/HttpRouter.h#L57-L64) to add [SIMD-accelerated route parameter decoding](https://github.com/oven-sh/bun/blob/main/src/bun.js/bindings/decodeURIComponentSIMD.cpp#L21-L271) and [JavaScriptCore structure caching](https://github.com/oven-sh/bun/blob/main/src/bun.js/bindings/ServerRouteList.cpp#L100-L101) to push the performance limits of what modern hardware allows.
-
-### `fetch` request handler
-
-The `fetch` handler handles incoming requests that weren't matched by any route. It receives a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object and returns a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) or [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
-
-```ts
-Bun.serve({
- fetch(req) {
- const url = new URL(req.url);
- if (url.pathname === "/") return new Response("Home page!");
- if (url.pathname === "/blog") return new Response("Blog!");
- return new Response("404!");
- },
-});
-```
-
-The `fetch` handler supports async/await:
-
-```ts
-import { sleep, serve } from "bun";
-serve({
- async fetch(req) {
- const start = performance.now();
- await sleep(10);
- const end = performance.now();
- return new Response(`Slept for ${end - start}ms`);
- },
-});
-```
-
-Promise-based responses are also supported:
-
-```ts
-Bun.serve({
- fetch(req) {
- // Forward the request to another server.
- return fetch("https://example.com");
- },
-});
-```
-
-You can also access the `Server` object from the `fetch` handler. It's the second argument passed to the `fetch` function.
-
-```ts
-// `server` is passed in as the second argument to `fetch`.
-const server = Bun.serve({
- fetch(req, server) {
- const ip = server.requestIP(req);
- return new Response(`Your IP is ${ip.address}`);
- },
-});
-```
-
-### Changing the `port` and `hostname`
-
-To configure which port and hostname the server will listen on, set `port` and `hostname` in the options object.
-
-```ts
-Bun.serve({
- port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
- hostname: "mydomain.com", // defaults to "0.0.0.0"
- fetch(req) {
- return new Response("404!");
- },
-});
-```
-
-To randomly select an available port, set `port` to `0`.
-
-```ts
-const server = Bun.serve({
- port: 0, // random port
- fetch(req) {
- return new Response("404!");
- },
-});
-
-// server.port is the randomly selected port
-console.log(server.port);
-```
-
-You can view the chosen port by accessing the `port` property on the server object, or by accessing the `url` property.
-
-```ts
-console.log(server.port); // 3000
-console.log(server.url); // http://localhost:3000
-```
-
-#### Configuring a default port
-
-Bun supports several options and environment variables to configure the default port. The default port is used when the `port` option is not set.
-
-- `--port` CLI flag
-
-```sh
-$ bun --port=4002 server.ts
-```
-
-- `BUN_PORT` environment variable
-
-```sh
-$ BUN_PORT=4002 bun server.ts
-```
-
-- `PORT` environment variable
-
-```sh
-$ PORT=4002 bun server.ts
-```
-
-- `NODE_PORT` environment variable
-
-```sh
-$ NODE_PORT=4002 bun server.ts
-```
-
-### Unix domain sockets
-
-To listen on a [unix domain socket](https://en.wikipedia.org/wiki/Unix_domain_socket), pass the `unix` option with the path to the socket.
-
-```ts
-Bun.serve({
- unix: "/tmp/my-socket.sock", // path to socket
- fetch(req) {
- return new Response(`404!`);
- },
-});
-```
-
-### Abstract namespace sockets
-
-Bun supports Linux abstract namespace sockets. To use an abstract namespace socket, prefix the `unix` path with a null byte.
-
-```ts
-Bun.serve({
- unix: "\0my-abstract-socket", // abstract namespace socket
- fetch(req) {
- return new Response(`404!`);
- },
-});
-```
-
-Unlike unix domain sockets, abstract namespace sockets are not bound to the filesystem and are automatically removed when the last reference to the socket is closed.
-
-## Error handling
-
-To activate development mode, set `development: true`.
-
-```ts
-Bun.serve({
- development: true,
- fetch(req) {
- throw new Error("woops!");
- },
-});
-```
-
-In development mode, Bun will surface errors in-browser with a built-in error page.
-
-{% image src="/images/exception_page.png" caption="Bun's built-in 500 page" /%}
-
-### `error` callback
-
-To handle server-side errors, implement an `error` handler. This function should return a `Response` to serve to the client when an error occurs. This response will supersede Bun's default error page in `development` mode.
-
-```ts
-Bun.serve({
- fetch(req) {
- throw new Error("woops!");
- },
- error(error) {
- return new Response(`
${error}\n${error.stack}
`, {
- headers: {
- "Content-Type": "text/html",
- },
- });
- },
-});
-```
-
-{% callout %}
-[Learn more about debugging in Bun](https://bun.com/docs/runtime/debugger)
-{% /callout %}
-
-The call to `Bun.serve` returns a `Server` object. To stop the server, call the `.stop()` method.
-
-```ts
-const server = Bun.serve({
- fetch() {
- return new Response("Bun!");
- },
-});
-
-server.stop();
-```
-
-## TLS
-
-Bun supports TLS out of the box, powered by [BoringSSL](https://boringssl.googlesource.com/boringssl). Enable TLS by passing in a value for `key` and `cert`; both are required to enable TLS.
-
-```ts-diff
- Bun.serve({
- fetch(req) {
- return new Response("Hello!!!");
- },
-
-+ tls: {
-+ key: Bun.file("./key.pem"),
-+ cert: Bun.file("./cert.pem"),
-+ }
- });
-```
-
-The `key` and `cert` fields expect the _contents_ of your TLS key and certificate, _not a path to it_. This can be a string, `BunFile`, `TypedArray`, or `Buffer`.
-
-```ts
-Bun.serve({
- fetch() {},
-
- tls: {
- // BunFile
- key: Bun.file("./key.pem"),
- // Buffer
- key: fs.readFileSync("./key.pem"),
- // string
- key: fs.readFileSync("./key.pem", "utf8"),
- // array of above
- key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")],
- },
-});
-```
-
-If your private key is encrypted with a passphrase, provide a value for `passphrase` to decrypt it.
-
-```ts-diff
- Bun.serve({
- fetch(req) {
- return new Response("Hello!!!");
- },
-
- tls: {
- key: Bun.file("./key.pem"),
- cert: Bun.file("./cert.pem"),
-+ passphrase: "my-secret-passphrase",
- }
- });
-```
-
-Optionally, you can override the trusted CA certificates by passing a value for `ca`. By default, the server will trust the list of well-known CAs curated by Mozilla. When `ca` is specified, the Mozilla list is overwritten.
-
-```ts-diff
- Bun.serve({
- fetch(req) {
- return new Response("Hello!!!");
- },
- tls: {
- key: Bun.file("./key.pem"), // path to TLS key
- cert: Bun.file("./cert.pem"), // path to TLS cert
-+ ca: Bun.file("./ca.pem"), // path to root CA certificate
- }
- });
-```
-
-To override Diffie-Hellman parameters:
-
-```ts
-Bun.serve({
- // ...
- tls: {
- // other config
- dhParamsFile: "/path/to/dhparams.pem", // path to Diffie Hellman parameters
- },
-});
-```
-
-### Server name indication (SNI)
-
-To configure the server name indication (SNI) for the server, set the `serverName` field in the `tls` object.
-
-```ts
-Bun.serve({
- // ...
- tls: {
- // ... other config
- serverName: "my-server.com", // SNI
- },
-});
-```
-
-To allow multiple server names, pass an array of objects to `tls`, each with a `serverName` field.
-
-```ts
-Bun.serve({
- // ...
- tls: [
- {
- key: Bun.file("./key1.pem"),
- cert: Bun.file("./cert1.pem"),
- serverName: "my-server1.com",
- },
- {
- key: Bun.file("./key2.pem"),
- cert: Bun.file("./cert2.pem"),
- serverName: "my-server2.com",
- },
- ],
-});
-```
-
-## idleTimeout
-
-To configure the idle timeout, set the `idleTimeout` field in Bun.serve.
-
-```ts
-Bun.serve({
- // 10 seconds:
- idleTimeout: 10,
-
- fetch(req) {
- return new Response("Bun!");
- },
-});
-```
-
-This is the maximum amount of time a connection is allowed to be idle before the server closes it. A connection is idling if there is no data sent or received.
-
-## export default syntax
-
-Thus far, the examples on this page have used the explicit `Bun.serve` API. Bun also supports an alternate syntax.
-
-```ts#server.ts
-import {type Serve} from "bun";
-
-export default {
- fetch(req) {
- return new Response("Bun!");
- },
-} satisfies Serve;
-```
-
-Instead of passing the server options into `Bun.serve`, `export default` it. This file can be executed as-is; when Bun sees a file with a `default` export containing a `fetch` handler, it passes it into `Bun.serve` under the hood.
-
-
-
-
-
-
-
-## Streaming files
-
-To stream a file, return a `Response` object with a `BunFile` object as the body.
-
-```ts
-Bun.serve({
- fetch(req) {
- return new Response(Bun.file("./hello.txt"));
- },
-});
-```
-
-{% callout %}
-⚡️ **Speed** — Bun automatically uses the [`sendfile(2)`](https://man7.org/linux/man-pages/man2/sendfile.2.html) system call when possible, enabling zero-copy file transfers in the kernel—the fastest way to send files.
-{% /callout %}
-
-You can send part of a file using the [`slice(start, end)`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice) method on the `Bun.file` object. This automatically sets the `Content-Range` and `Content-Length` headers on the `Response` object.
-
-```ts
-Bun.serve({
- fetch(req) {
- // parse `Range` header
- const [start = 0, end = Infinity] = req.headers
- .get("Range") // Range: bytes=0-100
- .split("=") // ["Range: bytes", "0-100"]
- .at(-1) // "0-100"
- .split("-") // ["0", "100"]
- .map(Number); // [0, 100]
-
- // return a slice of the file
- const bigFile = Bun.file("./big-video.mp4");
- return new Response(bigFile.slice(start, end));
- },
-});
-```
-
-## Server Lifecycle Methods
-
-### server.stop() - Stop the server
-
-To stop the server from accepting new connections:
-
-```ts
-const server = Bun.serve({
- fetch(req) {
- return new Response("Hello!");
- },
-});
-
-// Gracefully stop the server (waits for in-flight requests)
-await server.stop();
-
-// Force stop and close all active connections
-await server.stop(true);
-```
-
-By default, `stop()` allows in-flight requests and WebSocket connections to complete. Pass `true` to immediately terminate all connections.
-
-### server.ref() and server.unref() - Process lifecycle control
-
-Control whether the server keeps the Bun process alive:
-
-```ts
-// Don't keep process alive if server is the only thing running
-server.unref();
-
-// Restore default behavior - keep process alive
-server.ref();
-```
-
-### server.reload() - Hot reload handlers
-
-Update the server's handlers without restarting:
-
-```ts
-const server = Bun.serve({
- routes: {
- "/api/version": Response.json({ version: "v1" }),
- },
- fetch(req) {
- return new Response("v1");
- },
-});
-
-// Update to new handler
-server.reload({
- routes: {
- "/api/version": Response.json({ version: "v2" }),
- },
- fetch(req) {
- return new Response("v2");
- },
-});
-```
-
-This is useful for development and hot reloading. Only `fetch`, `error`, and `routes` can be updated.
-
-## Per-Request Controls
-
-
-
-### server.timeout(Request, seconds) - Custom request timeouts
-
-Set a custom idle timeout for individual requests:
-
-```ts
-const server = Bun.serve({
- fetch(req, server) {
- // Set 60 second timeout for this request
- server.timeout(req, 60);
-
- // If they take longer than 60 seconds to send the body, the request will be aborted
- await req.text();
-
- return new Response("Done!");
- },
-});
-```
-
-Pass `0` to disable the timeout for a request.
-
-### server.requestIP(Request) - Get client information
-
-Get client IP and port information:
-
-```ts
-const server = Bun.serve({
- fetch(req, server) {
- const address = server.requestIP(req);
- if (address) {
- return new Response(
- `Client IP: ${address.address}, Port: ${address.port}`,
- );
- }
- return new Response("Unknown client");
- },
-});
-```
-
-Returns `null` for closed requests or Unix domain sockets.
-
-## Working with Cookies
-
-Bun provides a built-in API for working with cookies in HTTP requests and responses. The `BunRequest` object includes a `cookies` property that provides a `CookieMap` for easily accessing and manipulating cookies. When using `routes`, `Bun.serve()` automatically tracks `request.cookies.set` and applies them to the response.
-
-### Reading cookies
-
-Read cookies from incoming requests using the `cookies` property on the `BunRequest` object:
-
-```ts
-Bun.serve({
- routes: {
- "/profile": req => {
- // Access cookies from the request
- const userId = req.cookies.get("user_id");
- const theme = req.cookies.get("theme") || "light";
-
- return Response.json({
- userId,
- theme,
- message: "Profile page",
- });
- },
- },
-});
-```
-
-### Setting cookies
-
-To set cookies, use the `set` method on the `CookieMap` from the `BunRequest` object.
-
-```ts
-Bun.serve({
- routes: {
- "/login": req => {
- const cookies = req.cookies;
-
- // Set a cookie with various options
- cookies.set("user_id", "12345", {
- maxAge: 60 * 60 * 24 * 7, // 1 week
- httpOnly: true,
- secure: true,
- path: "/",
- });
-
- // Add a theme preference cookie
- cookies.set("theme", "dark");
-
- // Modified cookies from the request are automatically applied to the response
- return new Response("Login successful");
- },
- },
-});
-```
-
-`Bun.serve()` automatically tracks modified cookies from the request and applies them to the response.
-
-### Deleting cookies
-
-To delete a cookie, use the `delete` method on the `request.cookies` (`CookieMap`) object:
-
-```ts
-Bun.serve({
- routes: {
- "/logout": req => {
- // Delete the user_id cookie
- req.cookies.delete("user_id", {
- path: "/",
- });
-
- return new Response("Logged out successfully");
- },
- },
-});
-```
-
-Deleted cookies become a `Set-Cookie` header on the response with the `maxAge` set to `0` and an empty `value`.
-
-## Server Metrics
-
-### server.pendingRequests and server.pendingWebSockets
-
-Monitor server activity with built-in counters:
-
-```ts
-const server = Bun.serve({
- fetch(req, server) {
- return new Response(
- `Active requests: ${server.pendingRequests}\n` +
- `Active WebSockets: ${server.pendingWebSockets}`,
- );
- },
-});
-```
-
-### server.subscriberCount(topic) - WebSocket subscribers
-
-Get count of subscribers for a WebSocket topic:
-
-```ts
-const server = Bun.serve({
- fetch(req, server) {
- const chatUsers = server.subscriberCount("chat");
- return new Response(`${chatUsers} users in chat`);
- },
- websocket: {
- message(ws) {
- ws.subscribe("chat");
- },
- },
-});
-```
-
-## WebSocket Configuration
-
-### server.publish(topic, data, compress) - WebSocket Message Publishing
-
-The server can publish messages to all WebSocket clients subscribed to a topic:
-
-```ts
-const server = Bun.serve({
- websocket: {
- message(ws) {
- // Publish to all "chat" subscribers
- server.publish("chat", "Hello everyone!");
- },
- },
-
- fetch(req) {
- // ...
- },
-});
-```
-
-The `publish()` method returns:
-
-- Number of bytes sent if successful
-- `0` if the message was dropped
-- `-1` if backpressure was applied
-
-### WebSocket Handler Options
-
-When configuring WebSockets, several advanced options are available through the `websocket` handler:
-
-```ts
-Bun.serve({
- websocket: {
- // Maximum message size (in bytes)
- maxPayloadLength: 64 * 1024,
-
- // Backpressure limit before messages are dropped
- backpressureLimit: 1024 * 1024,
-
- // Close connection if backpressure limit is hit
- closeOnBackpressureLimit: true,
-
- // Handler called when backpressure is relieved
- drain(ws) {
- console.log("Backpressure relieved");
- },
-
- // Enable per-message deflate compression
- perMessageDeflate: {
- compress: true,
- decompress: true,
- },
-
- // Send ping frames to keep connection alive
- sendPings: true,
-
- // Handlers for ping/pong frames
- ping(ws, data) {
- console.log("Received ping");
- },
- pong(ws, data) {
- console.log("Received pong");
- },
-
- // Whether server receives its own published messages
- publishToSelf: false,
- },
-});
-```
-
-## Benchmarks
-
-Below are Bun and Node.js implementations of a simple HTTP server that responds `Bun!` to each incoming `Request`.
-
-{% codetabs %}
-
-```ts#Bun
-Bun.serve({
- fetch(req: Request) {
- return new Response("Bun!");
- },
- port: 3000,
-});
-```
-
-```ts#Node
-require("http")
- .createServer((req, res) => res.end("Bun!"))
- .listen(8080);
-```
-
-{% /codetabs %}
-The `Bun.serve` server can handle roughly 2.5x more requests per second than Node.js on Linux.
-
-{% table %}
-
-- Runtime
-- Requests per second
-
----
-
-- Node 16
-- ~64,000
-
----
-
-- Bun
-- ~160,000
-
-{% /table %}
-
-{% image width="499" alt="image" src="https://user-images.githubusercontent.com/709451/162389032-fc302444-9d03-46be-ba87-c12bd8ce89a0.png" /%}
-
-## Reference
-
-{% details summary="See TypeScript definitions" %}
-
-```ts
-interface Server extends Disposable {
- /**
- * Stop the server from accepting new connections.
- * @param closeActiveConnections If true, immediately terminates all connections
- * @returns Promise that resolves when the server has stopped
- */
- stop(closeActiveConnections?: boolean): Promise;
-
- /**
- * Update handlers without restarting the server.
- * Only fetch and error handlers can be updated.
- */
- reload(options: Serve): void;
-
- /**
- * Make a request to the running server.
- * Useful for testing or internal routing.
- */
- fetch(request: Request | string): Response | Promise;
-
- /**
- * Upgrade an HTTP request to a WebSocket connection.
- * @returns true if upgrade successful, false if failed
- */
- upgrade(
- request: Request,
- options?: {
- headers?: Bun.HeadersInit;
- data?: T;
- },
- ): boolean;
-
- /**
- * Publish a message to all WebSocket clients subscribed to a topic.
- * @returns Bytes sent, 0 if dropped, -1 if backpressure applied
- */
- publish(
- topic: string,
- data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
- compress?: boolean,
- ): ServerWebSocketSendStatus;
-
- /**
- * Get count of WebSocket clients subscribed to a topic.
- */
- subscriberCount(topic: string): number;
-
- /**
- * Get client IP address and port.
- * @returns null for closed requests or Unix sockets
- */
- requestIP(request: Request): SocketAddress | null;
-
- /**
- * Set custom idle timeout for a request.
- * @param seconds Timeout in seconds, 0 to disable
- */
- timeout(request: Request, seconds: number): void;
-
- /**
- * Keep process alive while server is running.
- */
- ref(): void;
-
- /**
- * Allow process to exit if server is only thing running.
- */
- unref(): void;
-
- /** Number of in-flight HTTP requests */
- readonly pendingRequests: number;
-
- /** Number of active WebSocket connections */
- readonly pendingWebSockets: number;
-
- /** Server URL including protocol, hostname and port */
- readonly url: URL;
-
- /** Port server is listening on */
- readonly port: number;
-
- /** Hostname server is bound to */
- readonly hostname: string;
-
- /** Whether server is in development mode */
- readonly development: boolean;
-
- /** Server instance identifier */
- readonly id: string;
-}
-
-interface WebSocketHandler {
- /** Maximum WebSocket message size in bytes */
- maxPayloadLength?: number;
-
- /** Bytes of queued messages before applying backpressure */
- backpressureLimit?: number;
-
- /** Whether to close connection when backpressure limit hit */
- closeOnBackpressureLimit?: boolean;
-
- /** Called when backpressure is relieved */
- drain?(ws: ServerWebSocket): void | Promise;
-
- /** Seconds before idle timeout */
- idleTimeout?: number;
-
- /** Enable per-message deflate compression */
- perMessageDeflate?:
- | boolean
- | {
- compress?: WebSocketCompressor | boolean;
- decompress?: WebSocketCompressor | boolean;
- };
-
- /** Send ping frames to keep connection alive */
- sendPings?: boolean;
-
- /** Whether server receives its own published messages */
- publishToSelf?: boolean;
-
- /** Called when connection opened */
- open?(ws: ServerWebSocket): void | Promise;
-
- /** Called when message received */
- message(
- ws: ServerWebSocket,
- message: string | Buffer,
- ): void | Promise;
-
- /** Called when connection closed */
- close?(
- ws: ServerWebSocket,
- code: number,
- reason: string,
- ): void | Promise;
-
- /** Called when ping frame received */
- ping?(ws: ServerWebSocket, data: Buffer): void | Promise;
-
- /** Called when pong frame received */
- pong?(ws: ServerWebSocket, data: Buffer): void | Promise;
-}
-
-interface TLSOptions {
- /** Certificate authority chain */
- ca?: string | Buffer | BunFile | Array;
-
- /** Server certificate */
- cert?: string | Buffer | BunFile | Array;
-
- /** Path to DH parameters file */
- dhParamsFile?: string;
-
- /** Private key */
- key?: string | Buffer | BunFile | Array;
-
- /** Reduce TLS memory usage */
- lowMemoryMode?: boolean;
-
- /** Private key passphrase */
- passphrase?: string;
-
- /** OpenSSL options flags */
- secureOptions?: number;
-
- /** Server name for SNI */
- serverName?: string;
-}
-```
-
-{% /details %}
diff --git a/docs/api/import-meta.md b/docs/api/import-meta.md
deleted file mode 100644
index 7be078a2d1..0000000000
--- a/docs/api/import-meta.md
+++ /dev/null
@@ -1,69 +0,0 @@
-The `import.meta` object is a way for a module to access information about itself. It's part of the JavaScript language, but its contents are not standardized. Each "host" (browser, runtime, etc) is free to implement any properties it wishes on the `import.meta` object.
-
-Bun implements the following properties.
-
-```ts#/path/to/project/file.ts
-import.meta.dir; // => "/path/to/project"
-import.meta.file; // => "file.ts"
-import.meta.path; // => "/path/to/project/file.ts"
-import.meta.url; // => "file:///path/to/project/file.ts"
-
-import.meta.main; // `true` if this file is directly executed by `bun run`
- // `false` otherwise
-
-import.meta.resolve("zod"); // => "file:///path/to/project/node_modules/zod/index.js"
-```
-
-{% table %}
-
----
-
-- `import.meta.dir`
-- Absolute path to the directory containing the current file, e.g. `/path/to/project`. Equivalent to `__dirname` in CommonJS modules (and Node.js)
-
----
-
-- `import.meta.dirname`
-- An alias to `import.meta.dir`, for Node.js compatibility
-
----
-
-- `import.meta.env`
-- An alias to `process.env`.
-
----
-
-- `import.meta.file`
-- The name of the current file, e.g. `index.tsx`
-
----
-
-- `import.meta.path`
-- Absolute path to the current file, e.g. `/path/to/project/index.ts`. Equivalent to `__filename` in CommonJS modules (and Node.js)
-
----
-
-- `import.meta.filename`
-- An alias to `import.meta.path`, for Node.js compatibility
-
----
-
-- `import.meta.main`
-- Indicates whether the current file is the entrypoint to the current `bun` process. Is the file being directly executed by `bun run` or is it being imported?
-
----
-
-- `import.meta.resolve`
-- Resolve a module specifier (e.g. `"zod"` or `"./file.tsx"`) to a url. Equivalent to [`import.meta.resolve` in browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta#resolve)
-
- ```ts
- import.meta.resolve("zod");
- // => "file:///path/to/project/node_modules/zod/index.ts"
- ```
-
----
-
-- `import.meta.url`
-- A `string` url to the current file, e.g. `file:///path/to/project/index.ts`. Equivalent to [`import.meta.url` in browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta#url)
-
-{% /table %}
diff --git a/docs/benchmarks.md b/docs/benchmarks.md
deleted file mode 100644
index fd80513aef..0000000000
--- a/docs/benchmarks.md
+++ /dev/null
@@ -1,120 +0,0 @@
-Bun.js focuses on performance, developer experience, and compatibility with the JavaScript ecosystem.
-
-## HTTP Requests
-
-```ts
-// http.ts
-export default {
- port: 3000,
- fetch(request: Request) {
- return new Response("Hello World");
- },
-};
-
-// bun ./http.ts
-```
-
-| Requests per second | OS | CPU | Bun version |
-| ---------------------------------------------------------------------- | ----- | ------------------------------ | ----------- |
-| [260,000](https://twitter.com/jarredsumner/status/1512040623200616449) | macOS | Apple Silicon M1 Max | 0.0.76 |
-| [160,000](https://twitter.com/jarredsumner/status/1511988933587976192) | Linux | AMD Ryzen 5 3600 6-Core 2.2ghz | 0.0.76 |
-
-{% details summary="See benchmark details" %}
-Measured with [`http_load_test`](https://github.com/uNetworking/uSockets/blob/master/examples/http_load_test.c) by running:
-
-```bash
-$ ./http_load_test 20 127.0.0.1 3000
-```
-
-{% /details %}
-
-## File System
-
-`cat` clone that runs [2x faster than GNU cat](https://twitter.com/jarredsumner/status/1511707890708586496) for large files on Linux
-
-```js
-// cat.js
-import { resolve } from "path";
-import { write, stdout, file, argv } from "bun";
-
-const path = resolve(argv.at(-1));
-
-await write(
- // stdout is a Blob
- stdout,
- // file(path) returns a Blob - https://developer.mozilla.org/en-US/docs/Web/API/Blob
- file(path),
-);
-```
-
-Run this with `bun cat.js /path/to/big/file`.
-
-## Reading from standard input
-
-```ts
-for await (const line of console) {
- // line of text from stdin
- console.log(line);
-}
-```
-
-## React SSR
-
-```js
-import { renderToReadableStream } from "react-dom/server";
-
-const dt = new Intl.DateTimeFormat();
-
-export default {
- port: 3000,
- async fetch(request: Request) {
- return new Response(
- await renderToReadableStream(
-
-
- Hello World
-
-
-
Hello from React!
-
The date is {dt.format(new Date())}
-
- ,
- ),
- );
- },
-};
-```
-
-Write to stdout with `console.write`:
-
-```js
-// no trailing newline
-// works with strings and typed arrays
-console.write("Hello World!");
-```
-
-There are some more examples in the [examples](./examples) folder.
-
-PRs adding more examples are very welcome!
-
-## Fast paths for Web APIs
-
-Bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
-
-`Bun.file(path)` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) that represents a lazily-loaded file.
-
-When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call:
-
-```js
-const blob = Bun.file("input.txt");
-await Bun.write("output.txt", blob);
-```
-
-On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)).
-
-`Bun.write` also supports [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. It automatically converts to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
-
-```js
-// Eventually, this will stream the response to disk but today it buffers
-await Bun.write("index.html", await fetch("https://example.com"));
-```
diff --git a/docs/bun-flavored-toml.md b/docs/bun-flavored-toml.md
deleted file mode 100644
index ab7beb5920..0000000000
--- a/docs/bun-flavored-toml.md
+++ /dev/null
@@ -1,42 +0,0 @@
-[TOML](https://toml.io/) is a minimal configuration file format designed to be easy for humans to read.
-
-Bun implements a TOML parser with a few tweaks designed for better interoperability with INI files and with JavaScript.
-
-### ; and # are comments
-
-In Bun-flavored TOML, comments start with `#` or `;`
-
-```ini
-# This is a comment
-; This is also a comment
-```
-
-This matches the behavior of INI files.
-
-In TOML, comments start with `#`
-
-```toml
-# This is a comment
-```
-
-### String escape characters
-
-Bun-flavored adds a few more escape sequences to TOML to work better with JavaScript strings.
-
-```
-# Bun-flavored TOML extras
-\x{XX} - ASCII (U+00XX)
-\u{x+} - unicode (U+0000000X) - (U+XXXXXXXX)
-\v - vertical tab
-
-# Regular TOML
-\b - backspace (U+0008)
-\t - tab (U+0009)
-\n - linefeed (U+000A)
-\f - form feed (U+000C)
-\r - carriage return (U+000D)
-\" - quote (U+0022)
-\\ - backslash (U+005C)
-\uXXXX - unicode (U+XXXX)
-\UXXXXXXXX - unicode (U+XXXXXXXX)
-```
diff --git a/docs/bundler/bytecode.mdx b/docs/bundler/bytecode.mdx
new file mode 100644
index 0000000000..748d81eebd
--- /dev/null
+++ b/docs/bundler/bytecode.mdx
@@ -0,0 +1,465 @@
+---
+title: Bytecode Caching
+description: Speed up JavaScript execution with bytecode caching in Bun's bundler
+---
+
+Bytecode caching is a build-time optimization that dramatically improves application startup time by pre-compiling your JavaScript to bytecode. For example, when compiling TypeScript's `tsc` with bytecode enabled, startup time improves by **2x**.
+
+## Usage
+
+### Basic usage
+
+Enable bytecode caching with the `--bytecode` flag:
+
+```bash terminal icon="terminal"
+bun build ./index.ts --target=bun --bytecode --outdir=./dist
+```
+
+This generates two files:
+
+- `dist/index.js` - Your bundled JavaScript
+- `dist/index.jsc` - The bytecode cache file
+
+At runtime, Bun automatically detects and uses the `.jsc` file:
+
+```bash terminal icon="terminal"
+bun ./dist/index.js # Automatically uses index.jsc
+```
+
+### With standalone executables
+
+When creating executables with `--compile`, bytecode is embedded into the binary:
+
+```bash terminal icon="terminal"
+bun build ./cli.ts --compile --bytecode --outfile=mycli
+```
+
+The resulting executable contains both the code and bytecode, giving you maximum performance in a single file.
+
+### Combining with other optimizations
+
+Bytecode works great with minification and source maps:
+
+```bash terminal icon="terminal"
+bun build --compile --bytecode --minify --sourcemap ./cli.ts --outfile=mycli
+```
+
+- `--minify` reduces code size before generating bytecode (less code -> less bytecode)
+- `--sourcemap` preserves error reporting (errors still point to original source)
+- `--bytecode` eliminates parsing overhead
+
+## Performance impact
+
+The performance improvement scales with your codebase size:
+
+| Application size | Typical startup improvement |
+| ------------------------- | --------------------------- |
+| Small CLI (< 100 KB) | 1.5-2x faster |
+| Medium-large app (> 5 MB) | 2.5x-4x faster |
+
+Larger applications benefit more because they have more code to parse.
+
+## When to use bytecode
+
+### Great for:
+
+#### CLI tools
+
+- Invoked frequently (linters, formatters, git hooks)
+- Startup time is the entire user experience
+- Users notice the difference between 90ms and 45ms startup
+- Example: TypeScript compiler, Prettier, ESLint
+
+#### Build tools and task runners
+
+- Run hundreds or thousands of times during development
+- Milliseconds saved per run compound quickly
+- Developer experience improvement
+- Example: Build scripts, test runners, code generators
+
+#### Standalone executables
+
+- Distributed to users who care about snappy performance
+- Single-file distribution is convenient
+- File size less important than startup time
+- Example: CLIs distributed via npm or as binaries
+
+### Skip it for:
+
+- ❌ **Small scripts**
+- ❌ **Code that runs once**
+- ❌ **Development builds**
+- ❌ **Size-constrained environments**
+- ❌ **Code with top-level await** (not supported)
+
+## Limitations
+
+### CommonJS only
+
+Bytecode caching currently works with CommonJS output format. Bun's bundler automatically converts most ESM code to CommonJS, but **top-level await** is the exception:
+
+```js
+// This prevents bytecode caching
+const data = await fetch("https://api.example.com");
+export default data;
+```
+
+**Why**: Top-level await requires async module evaluation, which can't be represented in CommonJS. The module graph becomes asynchronous, and the CommonJS wrapper function model breaks down.
+
+**Workaround**: Move async initialization into a function:
+
+```js
+async function init() {
+ const data = await fetch("https://api.example.com");
+ return data;
+}
+
+export default init;
+```
+
+Now the module exports a function that the consumer can await when needed.
+
+### Version compatibility
+
+Bytecode is **not portable across Bun versions**. The bytecode format is tied to JavaScriptCore's internal representation, which changes between versions.
+
+When you update Bun, you must regenerate bytecode:
+
+```bash terminal icon="terminal"
+# After updating Bun
+bun build --bytecode ./index.ts --outdir=./dist
+```
+
+If bytecode doesn't match the current Bun version, it's automatically ignored and your code falls back to parsing the JavaScript source. Your app still runs - you just lose the performance optimization.
+
+**Best practice**: Generate bytecode as part of your CI/CD build process. Don't commit `.jsc` files to git. Regenerate them whenever you update Bun.
+
+### Source code still required
+
+- The `.js` file (your bundled source code)
+- The `.jsc` file (the bytecode cache)
+
+At runtime:
+
+1. Bun loads the `.js` file, sees a `@bytecode` pragma, and checks the `.jsc` file
+2. Bun loads the `.jsc` file
+3. Bun validates the bytecode hash matches the source
+4. If valid, Bun uses the bytecode
+5. If invalid, Bun falls back to parsing the source
+
+### Bytecode is not obfuscation
+
+Bytecode **does not obscure your source code**. It's an optimization, not a security measure.
+
+## Production deployment
+
+### Docker
+
+Include bytecode generation in your Dockerfile:
+
+```dockerfile Dockerfile icon="docker"
+FROM oven/bun:1 AS builder
+WORKDIR /app
+COPY package.json bun.lock ./
+RUN bun install --frozen-lockfile
+
+COPY . .
+RUN bun build --bytecode --minify --sourcemap \
+ --target=bun \
+ --outdir=./dist \
+ --compile \
+ ./src/server.ts --outfile=./dist/server
+
+FROM oven/bun:1 AS runner
+WORKDIR /app
+COPY --from=builder /dist/server /app/server
+CMD ["./server"]
+```
+
+The bytecode is architecture-independent.
+
+### CI/CD
+
+Generate bytecode during your build pipeline:
+
+```yaml workflow.yml icon="file-code"
+# GitHub Actions
+- name: Build with bytecode
+ run: |
+ bun install
+ bun build --bytecode --minify \
+ --outdir=./dist \
+ --target=bun \
+ ./src/index.ts
+```
+
+## Debugging
+
+### Verify bytecode is being used
+
+Check that the `.jsc` file exists:
+
+```bash terminal icon="terminal"
+ls -lh dist/
+```
+
+```txt
+-rw-r--r-- 1 user staff 245K index.js
+-rw-r--r-- 1 user staff 1.1M index.jsc
+```
+
+The `.jsc` file should be 2-8x larger than the `.js` file.
+
+To log if bytecode is being used, set `BUN_JSC_verboseDiskCache=1` in your environment.
+
+On success, it will log something like:
+
+```txt
+[Disk cache] cache hit for sourceCode
+```
+
+If you see a cache miss, it will log something like:
+
+```txt
+[Disk cache] cache miss for sourceCode
+```
+
+It's normal for it it to log a cache miss multiple times since Bun doesn't currently bytecode cache JavaScript code used in builtin modules.
+
+### Common issues
+
+**Bytecode silently ignored**: Usually caused by a Bun version update. The cache version doesn't match, so bytecode is rejected. Regenerate to fix.
+
+**File size too large**: This is expected. Consider:
+
+- Using `--minify` to reduce code size before bytecode generation
+- Compressing `.jsc` files for network transfer (gzip/brotli)
+- Evaluating if the startup performance gain is worth the size increase
+
+**Top-level await**: Not supported. Refactor to use async initialization functions.
+
+## What is bytecode?
+
+When you run JavaScript, the JavaScript engine doesn't execute your source code directly. Instead, it goes through several steps:
+
+1. **Parsing**: The engine reads your JavaScript source code and converts it into an Abstract Syntax Tree (AST)
+2. **Bytecode compilation**: The AST is compiled into bytecode - a lower-level representation that's faster to execute
+3. **Execution**: The bytecode is executed by the engine's interpreter or JIT compiler
+
+Bytecode is an intermediate representation - it's lower-level than JavaScript source code, but higher-level than machine code. Think of it as assembly language for a virtual machine. Each bytecode instruction represents a single operation like "load this variable," "add two numbers," or "call this function."
+
+This happens **every single time** you run your code. If you have a CLI tool that runs 100 times a day, your code gets parsed 100 times. If you have a serverless function with frequent cold starts, parsing happens on every cold start.
+
+With bytecode caching, Bun moves steps 1 and 2 to the build step. At runtime, the engine loads the pre-compiled bytecode and jumps straight to execution.
+
+### Why lazy parsing makes this even better
+
+Modern JavaScript engines use a clever optimization called **lazy parsing**. They don't parse all your code upfront - instead, functions are only parsed when they're first called:
+
+```js
+// Without bytecode caching:
+function rarely_used() {
+ // This 500-line function is only parsed
+ // when it's actually called
+}
+
+function main() {
+ console.log("Starting app");
+ // rarely_used() is never called, so it's never parsed
+}
+```
+
+This means parsing overhead isn't just a startup cost - it happens throughout your application's lifetime as different code paths execute. With bytecode caching, **all functions are pre-compiled**, even the ones that are lazily parsed. The parsing work happens once at build time instead of being distributed throughout your application's execution.
+
+## The bytecode format
+
+### Inside a .jsc file
+
+A `.jsc` file contains a serialized bytecode structure. Understanding what's inside helps explain both the performance benefits and the file size tradeoff.
+
+**Header section** (validated on every load):
+
+- **Cache version**: A hash tied to the JavaScriptCore framework version. This ensures bytecode generated with one version of Bun only runs with that exact version.
+- **Code block type tag**: Identifies whether this is a Program, Module, Eval, or Function code block.
+
+**SourceCodeKey** (validates bytecode matches source):
+
+- **Source code hash**: A hash of the original JavaScript source code. Bun verifies this matches before using the bytecode.
+- **Source code length**: The exact length of the source, for additional validation.
+- **Compilation flags**: Critical compilation context like strict mode, whether it's a script vs module, eval context type, etc. The same source code compiled with different flags produces different bytecode.
+
+**Bytecode instructions**:
+
+- **Instruction stream**: The actual bytecode opcodes - the compiled representation of your JavaScript. This is a variable-length sequence of bytecode instructions.
+- **Metadata table**: Each opcode has associated metadata - things like profiling counters, type hints, and execution counts (even if not yet populated).
+- **Jump targets**: Pre-computed addresses for control flow (if/else, loops, switch statements).
+- **Switch tables**: Optimized lookup tables for switch statements.
+
+**Constants and identifiers**:
+
+- **Constant pool**: All literal values in your code - numbers, strings, booleans, null, undefined. These are stored as actual JavaScript values (JSValues) so they don't need to be parsed from source at runtime.
+- **Identifier table**: All variable and function names used in the code. Stored as deduplicated strings.
+- **Source code representation markers**: Flags indicating how constants should be represented (as integers, doubles, big ints, etc.).
+
+**Function metadata** (for each function in your code):
+
+- **Register allocation**: How many registers (local variables) the function needs - `thisRegister`, `scopeRegister`, `numVars`, `numCalleeLocals`, `numParameters`.
+- **Code features**: A bitmask of function characteristics: is it a constructor? an arrow function? does it use `super`? does it have tail calls? These affect how the function is executed.
+- **Lexically scoped features**: Strict mode and other lexical context.
+- **Parse mode**: The mode in which the function was parsed (normal, async, generator, async generator).
+
+**Nested structures**:
+
+- **Function declarations and expressions**: Each nested function gets its own bytecode block, recursively. A file with 100 functions has 100 separate bytecode blocks, all nested in the structure.
+- **Exception handlers**: Try/catch/finally blocks with their boundaries and handler addresses pre-computed.
+- **Expression info**: Maps bytecode positions back to source code locations for error reporting and debugging.
+
+### What bytecode does NOT contain
+
+Importantly, **bytecode does not embed your source code**. Instead:
+
+- The JavaScript source is stored separately (in the `.js` file)
+- The bytecode only stores a hash and length of the source
+- At load time, Bun validates the bytecode matches the current source code
+
+This is why you need to deploy both the `.js` and `.jsc` files. The `.jsc` file is useless without its corresponding `.js` file.
+
+## The tradeoff: file size
+
+Bytecode files are significantly larger than source code - typically 2-8x larger.
+
+### Why is bytecode so much larger?
+
+**Bytecode instructions are verbose**:
+A single line of minified JavaScript might compile to dozens of bytecode instructions. For example:
+
+```js
+const sum = arr.reduce((a, b) => a + b, 0);
+```
+
+Compiles to bytecode that:
+
+- Loads the `arr` variable
+- Gets the `reduce` property
+- Creates the arrow function (which itself has bytecode)
+- Loads the initial value `0`
+- Sets up the call with the right number of arguments
+- Actually performs the call
+- Stores the result in `sum`
+
+Each of these steps is a separate bytecode instruction with its own metadata.
+
+**Constant pools store everything**:
+Every string literal, number, property name - everything gets stored in the constant pool. Even if your source code has `"hello"` a hundred times, the constant pool stores it once, but the identifier table and constant references add overhead.
+
+**Per-function metadata**:
+Each function - even small one-line functions - gets its own complete metadata:
+
+- Register allocation info
+- Code features bitmask
+- Parse mode
+- Exception handlers
+- Expression info for debugging
+
+A file with 1,000 small functions has 1,000 sets of metadata.
+
+**Profiling data structures**:
+Even though profiling data isn't populated yet, the _structures_ to hold profiling data are allocated. This includes:
+
+- Value profile slots (tracking what types flow through each operation)
+- Array profile slots (tracking array access patterns)
+- Binary arithmetic profile slots (tracking number types in math operations)
+- Unary arithmetic profile slots
+
+These take up space even when empty.
+
+**Pre-computed control flow**:
+Jump targets, switch tables, and exception handler boundaries are all pre-computed and stored. This makes execution faster but increases file size.
+
+### Mitigation strategies
+
+**Compression**:
+Bytecode compresses extremely well with gzip/brotli (60-70% compression). The repetitive structure and metadata compress efficiently.
+
+**Minification first**:
+Using `--minify` before bytecode generation helps:
+
+- Shorter identifiers → smaller identifier table
+- Dead code elimination → less bytecode generated
+- Constant folding → fewer constants in the pool
+
+**The tradeoff**:
+You're trading 2-4x larger files for 2-4x faster startup. For CLIs, this is usually worth it. For long-running servers where a few megabytes of disk space don't matter, it's even less of an issue.
+
+## Versioning and portability
+
+### Cross-architecture portability: ✅
+
+Bytecode is **architecture-independent**. You can:
+
+- Build on macOS ARM64, deploy to Linux x64
+- Build on Linux x64, deploy to AWS Lambda ARM64
+- Build on Windows x64, deploy to macOS ARM64
+
+The bytecode contains abstract instructions that work on any architecture. Architecture-specific optimizations happen during JIT compilation at runtime, not in the cached bytecode.
+
+### Cross-version portability: ❌
+
+Bytecode is **not stable across Bun versions**. Here's why:
+
+**Bytecode format changes**:
+JavaScriptCore's bytecode format evolves. New opcodes get added, old ones get removed or changed, metadata structures change. Each version of JavaScriptCore has a different bytecode format.
+
+**Version validation**:
+The cache version in the `.jsc` file header is a hash of the JavaScriptCore framework. When Bun loads bytecode:
+
+1. It extracts the cache version from the `.jsc` file
+2. It computes the current JavaScriptCore version
+3. If they don't match, the bytecode is **silently rejected**
+4. Bun falls back to parsing the `.js` source code
+
+Your application still runs - you just lose the performance optimization.
+
+**Graceful degradation**:
+This design means bytecode caching "fails open" - if anything goes wrong (version mismatch, corrupted file, missing file), your code still runs normally. You might see slower startup, but you won't see errors.
+
+## Unlinked vs. linked bytecode
+
+JavaScriptCore makes a crucial distinction between "unlinked" and "linked" bytecode. This separation is what makes bytecode caching possible:
+
+### Unlinked bytecode (what's cached)
+
+The bytecode saved in `.jsc` files is **unlinked bytecode**. It contains:
+
+- The compiled bytecode instructions
+- Structural information about the code
+- Constants and identifiers
+- Control flow information
+
+But it **doesn't** contain:
+
+- Pointers to actual runtime objects
+- JIT-compiled machine code
+- Profiling data from previous runs
+- Call link information (which functions call which)
+
+Unlinked bytecode is **immutable and shareable**. Multiple executions of the same code can all reference the same unlinked bytecode.
+
+### Linked bytecode (runtime execution)
+
+When Bun runs bytecode, it "links" it - creating a runtime wrapper that adds:
+
+- **Call link information**: As your code runs, the engine learns which functions call which and optimizes those call sites.
+- **Profiling data**: The engine tracks how many times each instruction executes, what types of values flow through the code, array access patterns, etc.
+- **JIT compilation state**: References to baseline JIT or optimizing JIT (DFG/FTL) compiled versions of hot code.
+- **Runtime objects**: Pointers to actual JavaScript objects, prototypes, scopes, etc.
+
+This linked representation is created fresh every time you run your code. This allows:
+
+1. **Caching the expensive work** (parsing and compilation to unlinked bytecode)
+2. **Still collecting runtime profiling data** to guide optimizations
+3. **Still applying JIT optimizations** based on actual execution patterns
+
+Bytecode caching moves expensive work (parsing and compiling to bytecode) from runtime to build time. For applications that start frequently, this can halve your startup time at the cost of larger files on disk.
+
+For production CLIs and serverless deployments, the combination of `--bytecode --minify --sourcemap` gives you the best performance while maintaining debuggability.
diff --git a/docs/bundler/css.md b/docs/bundler/css.mdx
similarity index 86%
rename from docs/bundler/css.md
rename to docs/bundler/css.mdx
index 6bb0fa5b6d..628a9fa4b8 100644
--- a/docs/bundler/css.md
+++ b/docs/bundler/css.mdx
@@ -1,3 +1,8 @@
+---
+title: CSS
+description: Bun's bundler has built-in support for CSS with modern features
+---
+
Bun's bundler has built-in support for CSS with the following features:
- Transpiling modern/future features to work on all browsers (including vendor prefixing)
@@ -9,11 +14,11 @@ Bun's bundler has built-in support for CSS with the following features:
Bun's CSS bundler lets you use modern/future CSS features without having to worry about browser compatibility — all thanks to its transpiling and vendor prefixing features which are enabled by default.
-Bun's CSS parser and bundler is a direct Rust → Zig port of [LightningCSS](https://lightningcss.dev/), with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers.
+Bun's CSS parser and bundler is a direct Rust → Zig port of LightningCSS, with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers.
-A huge thanks goes to the amazing work from the authors of [LightningCSS](https://lightningcss.dev/) and [esbuild](https://esbuild.github.io/).
+A huge thanks goes to the amazing work from the authors of LightningCSS and esbuild.
-### Browser Compatibility
+## Browser Compatibility
By default, Bun's CSS bundler targets the following browsers:
@@ -23,13 +28,13 @@ By default, Bun's CSS bundler targets the following browsers:
- Chrome 87+
- Safari 14+
-### Syntax Lowering
+## Syntax Lowering
-#### Nesting
+### Nesting
The CSS Nesting specification allows you to write more concise and intuitive stylesheets by nesting selectors inside one another. Instead of repeating parent selectors across your CSS file, you can write child styles directly within their parent blocks.
-```css
+```css title="styles.css" icon="file-code"
/* With nesting */
.card {
background: white;
@@ -48,7 +53,7 @@ The CSS Nesting specification allows you to write more concise and intuitive sty
Bun's CSS bundler automatically converts this nested syntax into traditional flat CSS that works in all browsers:
-```css
+```css title="styles.css" icon="file-code"
/* Compiled output */
.card {
background: white;
@@ -67,7 +72,7 @@ Bun's CSS bundler automatically converts this nested syntax into traditional fla
You can also nest media queries and other at-rules inside selectors, eliminating the need to repeat selector patterns:
-```css
+```css title="styles.css" icon="file-code"
.responsive-element {
display: block;
@@ -79,7 +84,7 @@ You can also nest media queries and other at-rules inside selectors, eliminating
This compiles to:
-```css
+```css title="styles.css" icon="file-code"
.responsive-element {
display: block;
}
@@ -91,11 +96,11 @@ This compiles to:
}
```
-#### Color mix
+### Color mix
The `color-mix()` function gives you an easy way to blend two colors together according to a specified ratio in a chosen color space. This powerful feature lets you create color variations without manually calculating the resulting values.
-```css
+```css title="styles.css" icon="file-code"
.button {
/* Mix blue and red in the RGB color space with a 30/70 proportion */
background-color: color-mix(in srgb, blue 30%, red);
@@ -109,7 +114,7 @@ The `color-mix()` function gives you an easy way to blend two colors together ac
Bun's CSS bundler evaluates these color mixes at build time when all color values are known (not CSS variables), generating static color values that work in all browsers:
-```css
+```css title="styles.css" icon="file-code"
.button {
/* Computed to the exact resulting color */
background-color: #b31a1a;
@@ -122,11 +127,11 @@ Bun's CSS bundler evaluates these color mixes at build time when all color value
This feature is particularly useful for creating color systems with programmatically derived shades, tints, and accents without needing preprocessors or custom tooling.
-#### Relative colors
+### Relative colors
CSS now allows you to modify individual components of a color using relative color syntax. This powerful feature lets you create color variations by adjusting specific attributes like lightness, saturation, or individual channels without having to recalculate the entire color.
-```css
+```css title="styles.css" icon="file-code"
.theme-color {
/* Start with a base color and increase lightness by 15% */
--accent: lch(from purple calc(l + 15%) c h);
@@ -147,27 +152,23 @@ Bun's CSS bundler computes these relative color modifications at build time (whe
This approach is extremely useful for theme generation, creating accessible color variants, or building color scales based on mathematical relationships instead of hard-coding each value.
-#### LAB colors
+### LAB colors
Modern CSS supports perceptually uniform color spaces like LAB, LCH, OKLAB, and OKLCH that offer significant advantages over traditional RGB. These color spaces can represent colors outside the standard RGB gamut, resulting in more vibrant and visually consistent designs.
-```css
+```css title="styles.css" icon="file-code"
.vibrant-element {
/* A vibrant red that exceeds sRGB gamut boundaries */
color: lab(55% 78 35);
/* A smooth gradient using perceptual color space */
- background: linear-gradient(
- to right,
- oklch(65% 0.25 10deg),
- oklch(65% 0.25 250deg)
- );
+ background: linear-gradient(to right, oklch(65% 0.25 10deg), oklch(65% 0.25 250deg));
}
```
Bun's CSS bundler automatically converts these advanced color formats to backwards-compatible alternatives for browsers that don't yet support them:
-```css
+```css title="styles.css" icon="file-code"
.vibrant-element {
/* Fallback to closest RGB approximation */
color: #ff0f52;
@@ -177,21 +178,17 @@ Bun's CSS bundler automatically converts these advanced color formats to backwar
color: lab(55% 78 35);
background: linear-gradient(to right, #cd4e15, #3887ab);
- background: linear-gradient(
- to right,
- oklch(65% 0.25 10deg),
- oklch(65% 0.25 250deg)
- );
+ background: linear-gradient(to right, oklch(65% 0.25 10deg), oklch(65% 0.25 250deg));
}
```
This layered approach ensures optimal color rendering across all browsers while allowing you to use the latest color technologies in your designs.
-#### Color function
+### Color function
The `color()` function provides a standardized way to specify colors in various predefined color spaces, expanding your design options beyond the traditional RGB space. This allows you to access wider color gamuts and create more vibrant designs.
-```css
+```css title="styles.css" icon="file-code"
.vivid-element {
/* Using the Display P3 color space for wider gamut colors */
color: color(display-p3 1 0.1 0.3);
@@ -203,7 +200,7 @@ The `color()` function provides a standardized way to specify colors in various
For browsers that don't support these advanced color functions yet, Bun's CSS bundler provides appropriate RGB fallbacks:
-```css
+```css title="styles.css" icon="file-code"
.vivid-element {
/* RGB fallback first for maximum compatibility */
color: #fa1a4c;
@@ -217,11 +214,11 @@ For browsers that don't support these advanced color functions yet, Bun's CSS bu
This functionality lets you use modern color spaces immediately while ensuring your designs remain functional across all browsers, with optimal colors displayed in supporting browsers and reasonable approximations elsewhere.
-#### HWB colors
+### HWB colors
The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to express colors based on how much white or black is mixed with a pure hue. Many designers find this approach more natural for creating color variations compared to manipulating RGB or HSL values.
-```css
+```css title="styles.css" icon="file-code"
.easy-theming {
/* Pure cyan with no white or black added */
--primary: hwb(180 0% 0%);
@@ -239,7 +236,7 @@ The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to exp
Bun's CSS bundler automatically converts HWB colors to RGB for compatibility with all browsers:
-```css
+```css title="styles.css" icon="file-code"
.easy-theming {
--primary: #00ffff;
--primary-light: #33ffff;
@@ -250,11 +247,11 @@ Bun's CSS bundler automatically converts HWB colors to RGB for compatibility wit
The HWB model makes it particularly easy to create systematic color variations for design systems, providing a more intuitive approach to creating consistent tints and shades than working directly with RGB or HSL values.
-#### Color notation
+### Color notation
Modern CSS has introduced more intuitive and concise ways to express colors. Space-separated color syntax eliminates the need for commas in RGB and HSL values, while hex colors with alpha channels provide a compact way to specify transparency.
-```css
+```css title="styles.css" icon="file-code"
.modern-styling {
/* Space-separated RGB notation (no commas) */
color: rgb(50 100 200);
@@ -272,7 +269,7 @@ Modern CSS has introduced more intuitive and concise ways to express colors. Spa
Bun's CSS bundler automatically converts these modern color formats to ensure compatibility with older browsers:
-```css
+```css title="styles.css" icon="file-code"
.modern-styling {
/* Converted to comma format for older browsers */
color: rgb(50, 100, 200);
@@ -289,11 +286,11 @@ Bun's CSS bundler automatically converts these modern color formats to ensure co
This conversion process lets you write cleaner, more modern CSS while ensuring your styles work correctly across all browsers.
-#### light-dark() color function
+### light-dark() color function
The `light-dark()` function provides an elegant solution for implementing color schemes that respect the user's system preference without requiring complex media queries. This function accepts two color values and automatically selects the appropriate one based on the current color scheme context.
-```css
+```css title="styles.css" icon="file-code"
:root {
/* Define color scheme support */
color-scheme: light dark;
@@ -318,7 +315,7 @@ The `light-dark()` function provides an elegant solution for implementing color
For browsers that don't support this feature yet, Bun's CSS bundler converts it to use CSS variables with proper fallbacks:
-```css
+```css title="styles.css" icon="file-code"
:root {
--lightningcss-light: initial;
--lightningcss-dark: ;
@@ -345,21 +342,19 @@ For browsers that don't support this feature yet, Bun's CSS bundler converts it
}
.themed-component {
- background-color: var(--lightningcss-light, #ffffff)
- var(--lightningcss-dark, #121212);
+ background-color: var(--lightningcss-light, #ffffff) var(--lightningcss-dark, #121212);
color: var(--lightningcss-light, #333333) var(--lightningcss-dark, #eeeeee);
- border-color: var(--lightningcss-light, #dddddd)
- var(--lightningcss-dark, #555555);
+ border-color: var(--lightningcss-light, #dddddd) var(--lightningcss-dark, #555555);
}
```
This approach gives you a clean way to handle light and dark themes without duplicating styles or writing complex media queries, while maintaining compatibility with browsers that don't yet support the feature natively.
-#### Logical properties
+### Logical properties
CSS logical properties let you define layout, spacing, and sizing relative to the document's writing mode and text direction rather than physical screen directions. This is crucial for creating truly international layouts that automatically adapt to different writing systems.
-```css
+```css title="styles.css" icon="file-code"
.multilingual-component {
/* Margin that adapts to writing direction */
margin-inline-start: 1rem;
@@ -378,7 +373,7 @@ CSS logical properties let you define layout, spacing, and sizing relative to th
For browsers that don't fully support logical properties, Bun's CSS bundler compiles them to physical properties with appropriate directional adjustments:
-```css
+```css title="styles.css" icon="file-code"
/* For left-to-right languages */
.multilingual-component:dir(ltr) {
margin-left: 1rem;
@@ -402,11 +397,11 @@ For browsers that don't fully support logical properties, Bun's CSS bundler comp
If the `:dir()` selector isn't supported, additional fallbacks are automatically generated to ensure your layouts work properly across all browsers and writing systems. This makes creating internationalized designs much simpler while maintaining compatibility with older browsers.
-#### :dir() selector
+### :dir() selector
The `:dir()` pseudo-class selector allows you to style elements based on their text direction (RTL or LTR), providing a powerful way to create direction-aware designs without JavaScript. This selector matches elements based on their directionality as determined by the document or explicit direction attributes.
-```css
+```css title="styles.css" icon="file-code"
/* Apply different styles based on text direction */
.nav-arrow:dir(ltr) {
transform: rotate(0deg);
@@ -428,7 +423,7 @@ The `:dir()` pseudo-class selector allows you to style elements based on their t
For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler converts it to the more widely supported `:lang()` selector with appropriate language mappings:
-```css
+```css title="styles.css" icon="file-code"
/* Converted to use language-based selectors as fallback */
.nav-arrow:lang(en, fr, de, es, it, pt, nl) {
transform: rotate(0deg);
@@ -449,11 +444,11 @@ For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler con
This conversion lets you write direction-aware CSS that works reliably across browsers, even those that don't yet support the `:dir()` selector natively. If multiple arguments to `:lang()` aren't supported, further fallbacks are automatically provided.
-#### :lang() selector
+### :lang() selector
The `:lang()` pseudo-class selector allows you to target elements based on the language they're in, making it easy to apply language-specific styling. Modern CSS allows the `:lang()` selector to accept multiple language codes, letting you group language-specific rules more efficiently.
-```css
+```css title="styles.css" icon="file-code"
/* Typography adjustments for CJK languages */
:lang(zh, ja, ko) {
line-height: 1.8;
@@ -472,7 +467,7 @@ blockquote:lang(de, nl, da, sv) {
For browsers that don't support multiple arguments in the `:lang()` selector, Bun's CSS bundler converts this syntax to use the `:is()` selector to maintain the same behavior:
-```css
+```css title="styles.css" icon="file-code"
/* Multiple languages grouped with :is() for better browser support */
:is(:lang(zh), :lang(ja), :lang(ko)) {
line-height: 1.8;
@@ -490,11 +485,11 @@ blockquote:is(:lang(de), :lang(nl), :lang(da), :lang(sv)) {
If needed, Bun can provide additional fallbacks for `:is()` as well, ensuring your language-specific styles work across all browsers. This approach simplifies creating internationalized designs with distinct typographic and styling rules for different language groups.
-#### :is() selector
+### :is() selector
The `:is()` pseudo-class function (formerly `:matches()`) allows you to create more concise and readable selectors by grouping multiple selectors together. It accepts a selector list as its argument and matches if any of the selectors in that list match, significantly reducing repetition in your CSS.
-```css
+```css title="styles.css" icon="file-code"
/* Instead of writing these separately */
/*
.article h1,
@@ -547,13 +542,17 @@ For browsers that don't support `:is()`, Bun's CSS bundler provides fallbacks us
}
```
-It's worth noting that the vendor-prefixed versions have some limitations compared to the standardized `:is()` selector, particularly with complex selectors. Bun handles these limitations intelligently, only using prefixed versions when they'll work correctly.
+
+ The vendor-prefixed versions have some limitations compared to the standardized `:is()` selector, particularly with
+ complex selectors. Bun handles these limitations intelligently, only using prefixed versions when they'll work
+ correctly.
+
-#### :not() selector
+### :not() selector
The `:not()` pseudo-class allows you to exclude elements that match a specific selector. The modern version of this selector accepts multiple arguments, letting you exclude multiple patterns with a single, concise selector.
-```css
+```css title="styles.css" icon="file-code"
/* Select all buttons except primary and secondary variants */
button:not(.primary, .secondary) {
background-color: #f5f5f5;
@@ -568,7 +567,7 @@ h2:not(.sidebar *, footer *) {
For browsers that don't support multiple arguments in `:not()`, Bun's CSS bundler converts this syntax to a more compatible form while preserving the same behavior:
-```css
+```css title="styles.css" icon="file-code"
/* Converted to use :not with :is() for compatibility */
button:not(:is(.primary, .secondary)) {
background-color: #f5f5f5;
@@ -582,7 +581,7 @@ h2:not(:is(.sidebar *, footer *)) {
And if `:is()` isn't supported, Bun can generate further fallbacks:
-```css
+```css title="styles.css" icon="file-code"
/* Even more fallbacks for maximum compatibility */
button:not(:-webkit-any(.primary, .secondary)) {
background-color: #f5f5f5;
@@ -602,11 +601,11 @@ button:not(:is(.primary, .secondary)) {
This conversion ensures your negative selectors work correctly across all browsers while maintaining the correct specificity and behavior of the original selector.
-#### Math functions
+### Math functions
CSS now includes a rich set of mathematical functions that let you perform complex calculations directly in your stylesheets. These include standard math functions (`round()`, `mod()`, `rem()`, `abs()`, `sign()`), trigonometric functions (`sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, `atan2()`), and exponential functions (`pow()`, `sqrt()`, `exp()`, `log()`, `hypot()`).
-```css
+```css title="styles.css" icon="file-code"
.dynamic-sizing {
/* Clamp a value between minimum and maximum */
width: clamp(200px, 50%, 800px);
@@ -625,7 +624,7 @@ CSS now includes a rich set of mathematical functions that let you perform compl
Bun's CSS bundler evaluates these mathematical expressions at build time when all values are known constants (not variables), resulting in optimized output:
-```css
+```css title="styles.css" icon="file-code"
.dynamic-sizing {
width: clamp(200px, 50%, 800px);
padding: 15px;
@@ -637,11 +636,11 @@ Bun's CSS bundler evaluates these mathematical expressions at build time when al
This approach lets you write more expressive and maintainable CSS with meaningful mathematical relationships, which then gets compiled to optimized values for maximum browser compatibility and performance.
-#### Media query ranges
+### Media query ranges
Modern CSS supports intuitive range syntax for media queries, allowing you to specify breakpoints using comparison operators like `<`, `>`, `<=`, and `>=` instead of the more verbose `min-` and `max-` prefixes. This syntax is more readable and matches how we normally think about values and ranges.
-```css
+```css title="styles.css" icon="file-code"
/* Modern syntax with comparison operators */
@media (width >= 768px) {
.container {
@@ -666,7 +665,7 @@ Modern CSS supports intuitive range syntax for media queries, allowing you to sp
Bun's CSS bundler converts these modern range queries to traditional media query syntax for compatibility with all browsers:
-```css
+```css title="styles.css" icon="file-code"
/* Converted to traditional min/max syntax */
@media (min-width: 768px) {
.container {
@@ -689,11 +688,11 @@ Bun's CSS bundler converts these modern range queries to traditional media query
This lets you write more intuitive and mathematical media queries while ensuring your stylesheets work correctly across all browsers, including those that don't support the modern range syntax.
-#### Shorthands
+### Shorthands
CSS has introduced several modern shorthand properties that improve code readability and maintainability. Bun's CSS bundler ensures these convenient shorthands work on all browsers by converting them to their longhand equivalents when needed.
-```css
+```css title="styles.css" icon="file-code"
/* Alignment shorthands */
.flex-container {
/* Shorthand for align-items and justify-items */
@@ -729,7 +728,7 @@ CSS has introduced several modern shorthand properties that improve code readabi
For browsers that don't support these modern shorthands, Bun converts them to their component longhand properties:
-```css
+```css title="styles.css" icon="file-code"
.flex-container {
/* Expanded alignment properties */
align-items: center;
@@ -766,11 +765,11 @@ For browsers that don't support these modern shorthands, Bun converts them to th
This conversion ensures your stylesheets remain clean and maintainable while providing the broadest possible browser compatibility.
-#### Double position gradients
+### Double position gradients
The double position gradient syntax is a modern CSS feature that allows you to create hard color stops in gradients by specifying the same color at two adjacent positions. This creates a sharp transition rather than a smooth fade, which is useful for creating stripes, color bands, and other multi-color designs.
-```css
+```css title="styles.css" icon="file-code"
.striped-background {
/* Creates a sharp transition from green to red at 30%-40% */
background: linear-gradient(
@@ -799,7 +798,7 @@ The double position gradient syntax is a modern CSS feature that allows you to c
For browsers that don't support this syntax, Bun's CSS bundler automatically converts it to the traditional format by duplicating color stops:
-```css
+```css title="styles.css" icon="file-code"
.striped-background {
background: linear-gradient(
to right,
@@ -830,11 +829,11 @@ For browsers that don't support this syntax, Bun's CSS bundler automatically con
This conversion lets you use the cleaner double position syntax in your source code while ensuring gradients display correctly in all browsers.
-#### system-ui font
+### system-ui font
The `system-ui` generic font family lets you use the device's native UI font, creating interfaces that feel more integrated with the operating system. This provides a more native look and feel without having to specify different font stacks for each platform.
-```css
+```css title="styles.css" icon="file-code"
.native-interface {
/* Use the system's default UI font */
font-family: system-ui;
@@ -848,7 +847,7 @@ The `system-ui` generic font family lets you use the device's native UI font, cr
For browsers that don't support `system-ui`, Bun's CSS bundler automatically expands it to a comprehensive cross-platform font stack:
-```css
+```css title="styles.css" icon="file-code"
.native-interface {
/* Expanded to support all major platforms */
font-family:
@@ -883,7 +882,7 @@ This approach gives you the simplicity of writing just `system-ui` in your sourc
## CSS Modules
-Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
+Bun's bundler also supports bundling CSS modules in addition to regular CSS with support for the following features:
- Automatically detecting CSS module files (`.module.css`) with zero configuration
- Composition (`composes` property)
@@ -894,17 +893,17 @@ A CSS module is a CSS file (with the `.module.css` extension) where are all clas
Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
-## Getting started
+### Getting started
Create a CSS file with the `.module.css` extension:
-```css
-/* styles.module.css */
+```css title="styles.module.css" icon="file-code"
.button {
color: red;
}
+```
-/* other-styles.module.css */
+```css title="other-styles.module.css" icon="file-code"
.button {
color: blue;
}
@@ -912,7 +911,7 @@ Create a CSS file with the `.module.css` extension:
You can then import this file, for example into a TSX file:
-```tsx
+```tsx title="app.tsx" icon="/icons/typescript.svg"
import styles from "./styles.module.css";
import otherStyles from "./other-styles.module.css";
@@ -926,10 +925,9 @@ export default function App() {
}
```
-The `styles` object from importing the CSS module file will be an object with all class names as keys and
-their unique identifiers as values:
+The styles object from importing the CSS module file will be an object with all class names as keys and their unique identifiers as values:
-```tsx
+```ts title="app.tsx" icon="/icons/typescript.svg"
import styles from "./styles.module.css";
import otherStyles from "./other-styles.module.css";
@@ -939,7 +937,7 @@ console.log(otherStyles);
This will output:
-```ts
+```ts title="app.tsx" icon="/icons/typescript.svg"
{
button: "button_123";
}
@@ -953,12 +951,11 @@ As you can see, the class names are unique to each file, avoiding any collisions
### Composition
-CSS modules allow you to _compose_ class selectors together. This lets you reuse style rules across multiple classes.
+CSS modules allow you to compose class selectors together. This lets you reuse style rules across multiple classes.
For example:
-```css
-/* styles.module.css */
+```css title="styles.module.css" icon="file-code"
.button {
composes: background;
color: red;
@@ -971,7 +968,7 @@ For example:
Would be the same as writing:
-```css
+```css title="styles.module.css" icon="file-code"
.button {
background-color: blue;
color: red;
@@ -982,13 +979,14 @@ Would be the same as writing:
}
```
-{% callout %}
There are a couple rules to keep in mind when using `composes`:
-- A `composes` property must come before any regular CSS properties or declarations
-- You can only use `composes` on a **simple selector with a single class name**:
+
+ **Composition Rules:** - A `composes` property must come before any regular CSS properties or declarations - You can
+ only use `composes` on a simple selector with a single class name
+
-```css
+```css title="styles.module.css" icon="file-code"
#button {
/* Invalid! `#button` is not a class selector */
composes: background;
@@ -1001,28 +999,26 @@ There are a couple rules to keep in mind when using `composes`:
}
```
-{% /callout %}
-
### Composing from a separate CSS module file
You can also compose from a separate CSS module file:
-```css
-/* background.module.css */
+```css title="background.module.css" icon="file-code"
.background {
background-color: blue;
}
+```
-/* styles.module.css */
+```css title="styles.module.css" icon="file-code"
.button {
composes: background from "./background.module.css";
color: red;
}
```
-{% callout %}
+
When composing classes from separate files, be sure that they do not contain the same properties.
-The CSS module spec says that composing classes from separate files with conflicting properties is
-undefined behavior, meaning that the output may differ and be unreliable.
-{% /callout %}
+The CSS module spec says that composing classes from separate files with conflicting properties is undefined behavior, meaning that the output may differ and be unreliable.
+
+
diff --git a/docs/bundler/css_modules.md b/docs/bundler/css_modules.md
deleted file mode 100644
index 271ab4621d..0000000000
--- a/docs/bundler/css_modules.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# CSS Modules
-
-Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
-
-- Automatically detecting CSS module files (`.module.css`) with zero configuration
-- Composition (`composes` property)
-- Importing CSS modules into JSX/TSX
-- Warnings/errors for invalid usages of CSS modules
-
-A CSS module is a CSS file (with the `.module.css` extension) where are all class names and animations are scoped to the file. This helps you avoid class name collisions as CSS declarations are globally scoped by default.
-
-Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
-
-## Getting started
-
-Create a CSS file with the `.module.css` extension:
-
-```css
-/* styles.module.css */
-.button {
- color: red;
-}
-
-/* other-styles.module.css */
-.button {
- color: blue;
-}
-```
-
-You can then import this file, for example into a TSX file:
-
-```tsx
-import styles from "./styles.module.css";
-import otherStyles from "./other-styles.module.css";
-
-export default function App() {
- return (
- <>
-
-
- >
- );
-}
-```
-
-The `styles` object from importing the CSS module file will be an object with all class names as keys and
-their unique identifiers as values:
-
-```tsx
-import styles from "./styles.module.css";
-import otherStyles from "./other-styles.module.css";
-
-console.log(styles);
-console.log(otherStyles);
-```
-
-This will output:
-
-```ts
-{
- button: "button_123";
-}
-
-{
- button: "button_456";
-}
-```
-
-As you can see, the class names are unique to each file, avoiding any collisions!
-
-### Composition
-
-CSS modules allow you to _compose_ class selectors together. This lets you reuse style rules across multiple classes.
-
-For example:
-
-```css
-/* styles.module.css */
-.button {
- composes: background;
- color: red;
-}
-
-.background {
- background-color: blue;
-}
-```
-
-Would be the same as writing:
-
-```css
-.button {
- background-color: blue;
- color: red;
-}
-
-.background {
- background-color: blue;
-}
-```
-
-{% callout %}
-There are a couple rules to keep in mind when using `composes`:
-
-- A `composes` property must come before any regular CSS properties or declarations
-- You can only use `composes` on a **simple selector with a single class name**:
-
-```css
-#button {
- /* Invalid! `#button` is not a class selector */
- composes: background;
-}
-
-.button,
-.button-secondary {
- /* Invalid! `.button, .button-secondary` is not a simple selector */
- composes: background;
-}
-```
-
-{% /callout %}
-
-### Composing from a separate CSS module file
-
-You can also compose from a separate CSS module file:
-
-```css
-/* background.module.css */
-.background {
- background-color: blue;
-}
-
-/* styles.module.css */
-.button {
- composes: background from "./background.module.css";
- color: red;
-}
-```
-
-{% callout %}
-When composing classes from separate files, be sure that they do not contain the same properties.
-
-The CSS module spec says that composing classes from separate files with conflicting properties is
-undefined behavior, meaning that the output may differ and be unreliable.
-{% /callout %}
diff --git a/docs/bundler/esbuild.mdx b/docs/bundler/esbuild.mdx
new file mode 100644
index 0000000000..d9cd38efd7
--- /dev/null
+++ b/docs/bundler/esbuild.mdx
@@ -0,0 +1,253 @@
+---
+title: esbuild
+description: Migration guide from esbuild to Bun's bundler
+---
+
+Bun's bundler API is inspired heavily by esbuild. Migrating to Bun's bundler from esbuild should be relatively painless. This guide will briefly explain why you might consider migrating to Bun's bundler and provide a side-by-side API comparison reference for those who are already familiar with esbuild's API.
+
+There are a few behavioral differences to note.
+
+
+ **Bundling by default.** Unlike esbuild, Bun always bundles by default. This is why the `--bundle` flag isn't
+ necessary in the Bun example. To transpile each file individually, use `Bun.Transpiler`.
+
+
+
+ **It's just a bundler.** Unlike esbuild, Bun's bundler does not include a built-in development server or file watcher.
+ It's just a bundler. The bundler is intended for use in conjunction with `Bun.serve` and other runtime APIs to achieve
+ the same effect. As such, all options relating to HTTP/file watching are not applicable.
+
+
+## Performance
+
+With a performance-minded API coupled with the extensively optimized Zig-based JS/TS parser, Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark.
+
+Bundling 10 copies of three.js from scratch, with sourcemaps and minification
+
+## CLI API
+
+Bun and esbuild both provide a command-line interface.
+
+```bash terminal icon="terminal"
+# esbuild
+esbuild --outdir=out --bundle
+
+# bun
+bun build --outdir=out
+```
+
+In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Other flags like `--outdir ` do accept an argument; these flags can be written as `--outdir out` or `--outdir=out`. Some flags like `--define` can be specified several times: `--define foo=bar --define bar=baz`.
+
+| esbuild | bun build | Notes |
+| ---------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `--bundle` | n/a | Bun always bundles, use `--no-bundle` to disable this behavior. |
+| `--define:K=V` | `--define K=V` | Small syntax difference; no colon. `esbuild --define:foo=bar` `bun build --define foo=bar` |
+| `--external:` | `--external ` | Small syntax difference; no colon. `esbuild --external:react` `bun build --external react` |
+| `--format` | `--format` | Bun supports `"esm"` and `"cjs"` currently, but more module formats are planned. esbuild defaults to `"iife"`. |
+| `--loader:.ext=loader` | `--loader .ext:loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.
The syntax for `--loader` is slightly different. `esbuild app.ts --bundle --loader:.svg=text` `bun build app.ts --loader .svg:text` |
+| `--minify` | `--minify` | No differences |
+| `--outdir` | `--outdir` | No differences |
+| `--outfile` | `--outfile` | No differences |
+| `--packages` | `--packages` | No differences |
+| `--platform` | `--target` | Renamed to `--target` for consistency with tsconfig. Does not support `neutral`. |
+| `--serve` | n/a | Not applicable |
+| `--sourcemap` | `--sourcemap` | No differences |
+| `--splitting` | `--splitting` | No differences |
+| `--target` | n/a | Not supported. Bun's bundler performs no syntactic down-leveling at this time. |
+| `--watch` | `--watch` | No differences |
+| `--allow-overwrite` | n/a | Overwriting is never allowed |
+| `--analyze` | n/a | Not supported |
+| `--asset-names` | `--asset-naming` | Renamed for consistency with naming in JS API |
+| `--banner` | `--banner` | Only applies to js bundles |
+| `--footer` | `--footer` | Only applies to js bundles |
+| `--certfile` | n/a | Not applicable |
+| `--charset=utf8` | n/a | Not supported |
+| `--chunk-names` | `--chunk-naming` | Renamed for consistency with naming in JS API |
+| `--color` | n/a | Always enabled |
+| `--drop` | `--drop` | |
+| `--entry-names` | `--entry-naming` | Renamed for consistency with naming in JS API |
+| `--global-name` | n/a | Not applicable, Bun does not support `iife` output at this time |
+| `--ignore-annotations` | `--ignore-dce-annotations` | |
+| `--inject` | n/a | Not supported |
+| `--jsx` | `--jsx-runtime ` | Supports `"automatic"` (uses jsx transform) and `"classic"` (uses `React.createElement`) |
+| `--jsx-dev` | n/a | Bun reads `compilerOptions.jsx` from `tsconfig.json` to determine a default. If `compilerOptions.jsx` is `"react-jsx"`, or if `NODE_ENV=production`, Bun will use the jsx transform. Otherwise, it uses `jsxDEV`. The bundler does not support `preserve`. |
+| `--jsx-factory` | `--jsx-factory` | |
+| `--jsx-fragment` | `--jsx-fragment` | |
+| `--jsx-import-source` | `--jsx-import-source` | |
+| `--jsx-side-effects` | n/a | JSX is always assumed to be side-effect-free |
+| `--keep-names` | n/a | Not supported |
+| `--keyfile` | n/a | Not applicable |
+| `--legal-comments` | n/a | Not supported |
+| `--log-level` | n/a | Not supported. This can be set in `bunfig.toml` as `logLevel`. |
+| `--log-limit` | n/a | Not supported |
+| `--log-override:X=Y` | n/a | Not supported |
+| `--main-fields` | n/a | Not supported |
+| `--mangle-cache` | n/a | Not supported |
+| `--mangle-props` | n/a | Not supported |
+| `--mangle-quoted` | n/a | Not supported |
+| `--metafile` | n/a | Not supported |
+| `--minify-whitespace` | `--minify-whitespace` | |
+| `--minify-identifiers` | `--minify-identifiers` | |
+| `--minify-syntax` | `--minify-syntax` | |
+| `--out-extension` | n/a | Not supported |
+| `--outbase` | `--root` | |
+| `--preserve-symlinks` | n/a | Not supported |
+| `--public-path` | `--public-path` | |
+| `--pure` | n/a | Not supported |
+| `--reserve-props` | n/a | Not supported |
+| `--resolve-extensions` | n/a | Not supported |
+| `--servedir` | n/a | Not applicable |
+| `--source-root` | n/a | Not supported |
+| `--sourcefile` | n/a | Not supported. Bun does not support stdin input yet. |
+| `--sourcemap` | `--sourcemap` | No differences |
+| `--sources-content` | n/a | Not supported |
+| `--supported` | n/a | Not supported |
+| `--tree-shaking` | n/a | Always true |
+| `--tsconfig` | `--tsconfig-override` | |
+| `--version` | n/a | Run `bun --version` to see the version of Bun. |
+
+## JavaScript API
+
+| esbuild.build() | Bun.build() | Notes |
+| ------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `absWorkingDir` | n/a | Always set to `process.cwd()` |
+| `alias` | n/a | Not supported |
+| `allowOverwrite` | n/a | Always false |
+| `assetNames` | `naming.asset` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.
`ts Bun.build({ entrypoints: ["./index.tsx"], naming: { asset: "[name].[ext]", }, }); ` |
+| `banner` | n/a | Not supported |
+| `bundle` | n/a | Always true. Use `Bun.Transpiler` to transpile without bundling. |
+| `charset` | n/a | Not supported |
+| `chunkNames` | `naming.chunk` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.
`ts Bun.build({ entrypoints: ["./index.tsx"], naming: { chunk: "[name].[ext]", }, }); ` |
+| `color` | n/a | Bun returns logs in the `logs` property of the build result. |
+| `conditions` | n/a | Not supported. Export conditions priority is determined by `target`. |
+| `define` | `define` | |
+| `drop` | n/a | Not supported |
+| `entryNames` | `naming` or `naming.entry` | Bun supports a `naming` key that can either be a string or an object. Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.
`ts Bun.build({ entrypoints: ["./index.tsx"], // when string, this is equivalent to entryNames naming: "[name].[ext]",
// granular naming options naming: { entry: "[name].[ext]", asset: "[name].[ext]", chunk: "[name].[ext]", }, }); ` |
+| `entryPoints` | `entrypoints` | Capitalization difference |
+| `external` | `external` | No differences |
+| `footer` | n/a | Not supported |
+| `format` | `format` | Only supports `"esm"` currently. Support for `"cjs"` and `"iife"` is planned. |
+| `globalName` | n/a | Not supported |
+| `ignoreAnnotations` | n/a | Not supported |
+| `inject` | n/a | Not supported |
+| `jsx` | `jsx` | Not supported in JS API, configure in `tsconfig.json` |
+| `jsxDev` | `jsxDev` | Not supported in JS API, configure in `tsconfig.json` |
+| `jsxFactory` | `jsxFactory` | Not supported in JS API, configure in `tsconfig.json` |
+| `jsxFragment` | `jsxFragment` | Not supported in JS API, configure in `tsconfig.json` |
+| `jsxImportSource` | `jsxImportSource` | Not supported in JS API, configure in `tsconfig.json` |
+| `jsxSideEffects` | `jsxSideEffects` | Not supported in JS API, configure in `tsconfig.json` |
+| `keepNames` | n/a | Not supported |
+| `legalComments` | n/a | Not supported |
+| `loader` | `loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented. |
+| `logLevel` | n/a | Not supported |
+| `logLimit` | n/a | Not supported |
+| `logOverride` | n/a | Not supported |
+| `mainFields` | n/a | Not supported |
+| `mangleCache` | n/a | Not supported |
+| `mangleProps` | n/a | Not supported |
+| `mangleQuoted` | n/a | Not supported |
+| `metafile` | n/a | Not supported |
+| `minify` | `minify` | In Bun, `minify` can be a boolean or an object.
// granular options minify: { identifiers: true, syntax: true, whitespace: true } }) ` |
+| `minifyIdentifiers` | `minify.identifiers` | See `minify` |
+| `minifySyntax` | `minify.syntax` | See `minify` |
+| `minifyWhitespace` | `minify.whitespace` | See `minify` |
+| `nodePaths` | n/a | Not supported |
+| `outExtension` | n/a | Not supported |
+| `outbase` | `root` | Different name |
+| `outdir` | `outdir` | No differences |
+| `outfile` | `outfile` | No differences |
+| `packages` | n/a | Not supported, use `external` |
+| `platform` | `target` | Supports `"bun"`, `"node"` and `"browser"` (the default). Does not support `"neutral"`. |
+| `plugins` | `plugins` | Bun's plugin API is a subset of esbuild's. Some esbuild plugins will work out of the box with Bun. |
+| `preserveSymlinks` | n/a | Not supported |
+| `publicPath` | `publicPath` | No differences |
+| `pure` | n/a | Not supported |
+| `reserveProps` | n/a | Not supported |
+| `resolveExtensions` | n/a | Not supported |
+| `sourceRoot` | n/a | Not supported |
+| `sourcemap` | `sourcemap` | Supports `"inline"`, `"external"`, and `"none"` |
+| `sourcesContent` | n/a | Not supported |
+| `splitting` | `splitting` | No differences |
+| `stdin` | n/a | Not supported |
+| `supported` | n/a | Not supported |
+| `target` | n/a | No support for syntax downleveling |
+| `treeShaking` | n/a | Always true |
+| `tsconfig` | n/a | Not supported |
+| `write` | n/a | Set to true if `outdir`/`outfile` is set, otherwise false |
+
+## Plugin API
+
+Bun's plugin API is designed to be esbuild compatible. Bun doesn't support esbuild's entire plugin API surface, but the core functionality is implemented. Many third-party esbuild plugins will work out of the box with Bun.
+
+
+ Long term, we aim for feature parity with esbuild's API, so if something doesn't work please file an issue to help us
+ prioritize.
+
+
+Plugins in Bun and esbuild are defined with a builder object.
+
+```ts title="myPlugin.ts" icon="/icons/typescript.svg"
+import type { BunPlugin } from "bun";
+
+const myPlugin: BunPlugin = {
+ name: "my-plugin",
+ setup(builder) {
+ // define plugin
+ },
+};
+```
+
+The builder object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use `config` (same thing but with Bun's `BuildConfig` format) instead.
+
+```ts title="myPlugin.ts" icon="/icons/typescript.svg"
+import type { BunPlugin } from "bun";
+const myPlugin: BunPlugin = {
+ name: "my-plugin",
+ setup(builder) {
+ builder.onResolve(
+ {
+ /* onResolve.options */
+ },
+ args => {
+ return {
+ /* onResolve.results */
+ };
+ },
+ );
+ builder.onLoad(
+ {
+ /* onLoad.options */
+ },
+ args => {
+ return {
+ /* onLoad.results */
+ };
+ },
+ );
+ },
+};
+```
+
+### onResolve
+
+
+ - 🟢 `filter` - 🟢 `namespace`
+
+ - 🟢 `path` - 🟢 `importer` - 🔴 `namespace` - 🔴 `resolveDir` - 🔴 `kind` - 🔴 `pluginData`
+
+
+ - 🟢 `namespace` - 🟢 `path` - 🔴 `errors` - 🔴 `external` - 🔴 `pluginData` - 🔴 `pluginName` - 🔴 `sideEffects` -
+ 🔴 `suffix` - 🔴 `warnings` - 🔴 `watchDirs` - 🔴 `watchFiles`
+
+
+
+### onLoad
+
+
+ - 🟢 `filter` - 🟢 `namespace`
+ - 🟢 `path` - 🔴 `namespace` - 🔴 `suffix` - 🔴 `pluginData`
+
+ - 🟢 `contents` - 🟢 `loader` - 🔴 `errors` - 🔴 `pluginData` - 🔴 `pluginName` - 🔴 `resolveDir` - 🔴 `warnings` -
+ 🔴 `watchDirs` - 🔴 `watchFiles`
+
+
diff --git a/docs/bundler/executables.md b/docs/bundler/executables.mdx
similarity index 68%
rename from docs/bundler/executables.md
rename to docs/bundler/executables.mdx
index 097c64f978..fb7059435f 100644
--- a/docs/bundler/executables.md
+++ b/docs/bundler/executables.mdx
@@ -1,33 +1,43 @@
+---
+title: "Single-file executable"
+description: "Generate standalone executables from TypeScript or JavaScript files with Bun"
+---
+
Bun's bundler implements a `--compile` flag for generating a standalone binary from a TypeScript or JavaScript file.
-{% codetabs %}
+
-```bash
-$ bun build ./cli.ts --compile --outfile mycli
+```bash terminal icon="terminal"
+bun build ./cli.ts --compile --outfile mycli
```
-```ts#cli.ts
+```ts cli.ts icon="/icons/typescript.svg"
console.log("Hello world!");
```
-{% /codetabs %}
+
This bundles `cli.ts` into an executable that can be executed directly:
+```bash terminal icon="terminal"
+./mycli
```
-$ ./mycli
+
+```txt
Hello world!
```
All imported files and packages are bundled into the executable, along with a copy of the Bun runtime. All built-in Bun and Node.js APIs are supported.
+---
+
## Cross-compile to other platforms
The `--target` flag lets you compile your standalone executable for a different operating system, architecture, or version of Bun than the machine you're running `bun build` on.
To build for Linux x64 (most servers):
-```sh
+```bash icon="terminal" terminal
bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp
# To support CPUs from before 2013, use the baseline version (nehalem)
@@ -40,14 +50,14 @@ bun build --compile --target=bun-linux-x64-modern ./index.ts --outfile myapp
To build for Linux ARM64 (e.g. Graviton or Raspberry Pi):
-```sh
+```bash icon="terminal" terminal
# Note: the default architecture is x64 if no architecture is specified.
bun build --compile --target=bun-linux-arm64 ./index.ts --outfile myapp
```
To build for Windows x64:
-```sh
+```bash icon="terminal" terminal
bun build --compile --target=bun-windows-x64 ./path/to/my/app.ts --outfile myapp
# To support CPUs from before 2013, use the baseline version (nehalem)
@@ -61,17 +71,17 @@ bun build --compile --target=bun-windows-x64-modern ./path/to/my/app.ts --outfil
To build for macOS arm64:
-```sh
+```bash icon="terminal" terminal
bun build --compile --target=bun-darwin-arm64 ./path/to/my/app.ts --outfile myapp
```
To build for macOS x64:
-```sh
+```bash icon="terminal" terminal
bun build --compile --target=bun-darwin-x64 ./path/to/my/app.ts --outfile myapp
```
-#### Supported targets
+### Supported targets
The order of the `--target` flag does not matter, as long as they're delimited by a `-`.
@@ -86,21 +96,32 @@ The order of the `--target` flag does not matter, as long as they're delimited b
| bun-linux-x64-musl | Linux | x64 | ✅ | ✅ | musl |
| bun-linux-arm64-musl | Linux | arm64 | ✅ | N/A | musl |
-On x64 platforms, Bun uses SIMD optimizations which require a modern CPU supporting AVX2 instructions. The `-baseline` build of Bun is for older CPUs that don't support these optimizations. Normally, when you install Bun we automatically detect which version to use but this can be harder to do when cross-compiling since you might not know the target CPU. You usually don't need to worry about it on Darwin x64, but it is relevant for Windows x64 and Linux x64. If you or your users see `"Illegal instruction"` errors, you might need to use the baseline version.
+
+ On x64 platforms, Bun uses SIMD optimizations which require a modern CPU supporting AVX2 instructions. The `-baseline`
+ build of Bun is for older CPUs that don't support these optimizations. Normally, when you install Bun we automatically
+ detect which version to use but this can be harder to do when cross-compiling since you might not know the target CPU.
+ You usually don't need to worry about it on Darwin x64, but it is relevant for Windows x64 and Linux x64. If you or
+ your users see `"Illegal instruction"` errors, you might need to use the baseline version.
+
+
+---
## Build-time constants
Use the `--define` flag to inject build-time constants into your executable, such as version numbers, build timestamps, or configuration values:
-```bash
-$ bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
+```bash icon="terminal" terminal
+bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
```
These constants are embedded directly into your compiled binary at build time, providing zero runtime overhead and enabling dead code elimination optimizations.
-{% callout type="info" %}
-For comprehensive examples and advanced patterns, see the [Build-time constants guide](/guides/runtime/build-time-constants).
-{% /callout %}
+
+ For comprehensive examples and advanced patterns, see the [Build-time constants
+ guide](https://bun.com/guides/runtime/build-time-constants).
+
+
+---
## Deploying to production
@@ -112,7 +133,7 @@ With compiled executables, you can move that cost from runtime to build-time.
When deploying to production, we recommend the following:
-```sh
+```bash icon="terminal" terminal
bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
```
@@ -120,17 +141,22 @@ bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
To improve startup time, enable bytecode compilation:
-```sh
+```bash icon="terminal" terminal
bun build --compile --minify --sourcemap --bytecode ./path/to/my/app.ts --outfile myapp
```
Using bytecode compilation, `tsc` starts 2x faster:
-{% image src="https://github.com/user-attachments/assets/dc8913db-01d2-48f8-a8ef-ac4e984f9763" width="689" /%}
+
+ 
+
Bytecode compilation moves parsing overhead for large input files from runtime to bundle time. Your app starts faster, in exchange for making the `bun build` command a little slower. It doesn't obscure source code.
-**Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is supported (which means no top-level-await). Let us know if you run into any issues!
+
+ **Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is
+ supported (which means no top-level-await). Let us know if you run into any issues!
+
### What do these flags do?
@@ -140,68 +166,77 @@ The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that erro
The `--bytecode` argument enables bytecode compilation. Every time you run JavaScript code in Bun, JavaScriptCore (the engine) will compile your source code into bytecode. We can move this parsing work from runtime to bundle time, saving you startup time.
+---
+
## Embedding runtime arguments
**`--compile-exec-argv="args"`** - Embed runtime arguments that are available via `process.execArgv`:
-```bash
+```bash icon="terminal" terminal
bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myapp
```
-```js
+```ts app.ts icon="/icons/typescript.svg"
// In the compiled app
console.log(process.execArgv); // ["--smol", "--user-agent=MyBot"]
```
+---
+
## Act as the Bun CLI
-{% note %}
-
-New in Bun v1.2.16
-
-{% /note %}
+New in Bun v1.2.16
You can run a standalone executable as if it were the `bun` CLI itself by setting the `BUN_BE_BUN=1` environment variable. When this variable is set, the executable will ignore its bundled entrypoint and instead expose all the features of Bun's CLI.
For example, consider an executable compiled from a simple script:
-```sh
-$ cat such-bun.js
-console.log("you shouldn't see this");
+```bash icon="terminal" terminal
+echo "console.log(\"you shouldn't see this\");" > such-bun.js
+bun build --compile ./such-bun.js
+```
-$ bun build --compile ./such-bun.js
- [3ms] bundle 1 modules
+```txt
+[3ms] bundle 1 modules
[89ms] compile such-bun
```
-Normally, running `./such-bun` with arguments would execute the script. However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
+Normally, running `./such-bun` with arguments would execute the script.
-```sh
+```bash icon="terminal" terminal
# Executable runs its own entrypoint by default
-$ ./such-bun install
-you shouldn't see this
+./such-bun install
+```
+```txt
+you shouldn't see this
+```
+
+However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
+
+```bash icon="terminal" terminal
# With the env var, the executable acts like the `bun` CLI
-$ BUN_BE_BUN=1 ./such-bun install
+bun_BE_BUN=1 ./such-bun install
+```
+
+```txt
bun install v1.2.16-canary.1 (1d1db811)
Checked 63 installs across 64 packages (no changes) [5.00ms]
```
This is useful for building CLI tools on top of Bun that may need to install packages, bundle dependencies, run different or local files and more without needing to download a separate binary or install bun.
+---
+
## Full-stack executables
-{% note %}
-
-New in Bun v1.2.17
-
-{% /note %}
+New in Bun v1.2.17
Bun's `--compile` flag can create standalone executables that contain both server and client code, making it ideal for full-stack applications. When you import an HTML file in your server code, Bun automatically bundles all frontend assets (JavaScript, CSS, etc.) and embeds them into the executable. When Bun sees the HTML import on the server, it kicks off a frontend build process to bundle JavaScript, CSS, and other assets.
-{% codetabs %}
+
-```ts#server.ts
+```ts server.ts icon="/icons/typescript.svg"
import { serve } from "bun";
import index from "./index.html";
@@ -215,12 +250,12 @@ const server = serve({
console.log(`Server running at http://localhost:${server.port}`);
```
-```html#index.html
+```html index.html icon="file-code"
My App
-
+