Bun 是采用 Zig 语言编写的高性能 “全家桶” JavaScript 运行时,官方称其为 "all-in-one JavaScript runtime"




bun is a new:

- JavaScript runtime with Web APIs like [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch), [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), and several more built-in. bun embeds JavaScriptCore, which tends to be faster and more memory efficient than more popular engines like V8 (though harder to embed)
- JavaScript/TypeScript/JSX transpiler
- JavaScript & CSS bundler
- Task runner for package.json scripts
- npm-compatible package manager

All in one fast & easy-to-use tool. Instead of 1,000 node_modules for development, you only need bun.

bun is experimental software. Join bun’s Discord for help and have a look at things that don’t work yet.

Today, bun's primary focus is bun.js: bun's JavaScript runtime.


Native: (macOS x64 & Silicon, Linux x64, Windows Subsystem for Linux)

  1. ```sh
  2. curl -fsSL https://bun.sh/install | bash
  3. ```

Homebrew: (MacOS and Linux)

  1. ```sh
  2. brew tap oven-sh/bun
  3. brew install bun
  4. ```

Docker: (Linux x64)

  1. ```sh
  2. docker pull jarredsumner/bun:edge
  3. docker run --rm --init --ulimit memlock=-1:-1 jarredsumner/bun:edge
  4. ```

If using Linux, kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.


To upgrade to the latest version of Bun, run:

  1. ```sh
  2. bun upgrade
  3. ```

Bun automatically releases a canary build on every commit to main. To upgrade to the latest canary build, run:

  1. ```sh
  2. bun upgrade --canary
  3. ```

Canary builds are released without automated tests

Table of Contents

  - Loaders
  - CSS in JS
    - [When platform is browser](#when-platform-is-browser)
    - [When platform is bun](#when-platform-is-bun)
    - Arch / Manjaro
    - OpenSUSE
  - [bun install](#bun-install)
    - [Configuring bun install with bunfig.toml](#configuring-bun-install-with-bunfigtoml)
    - Lockfile
    - Why is it fast?
    - Cache
  - [bun run](#bun-run)
  - [bun create](#bun-create)
    - Usage
    - Local templates
    - Flags
    - Config
    - [How bun create works](#how-bun-create-works)
  - [bun init](#bun-init)
  - [bun bun](#bun-bun)
    - Why bundle?
    - [What is .bun?](#what-is-bun)
    - Advanced
  - [bun upgrade](#bun-upgrade)
  - [bun completions](#bun-completions)
- [Bun.serve - fast HTTP server](#bunserve---fast-http-server)
  - Usage
- [Bun.write – optimizing I/O](#bunwrite--optimizing-io)
- [Bun.spawn - spawn processes](#bunspawn--spawn-a-process)
- [Bun.which - find the path to a bin](#bunwhich--find-the-path-to-a-binary)
  - [Database](#database)
  - Statement
    - Statement.all
    - Statement.get
    - Statement.run
  - Datatypes
- [bun:ffi (Foreign Functions Interface)](#bunffi-foreign-functions-interface)
  - Usage
  - [Supported FFI types (FFIType)](#supported-ffi-types-ffitype)
  - [Strings (CString)](#strings-cstring)
  - [Function pointers (CFunction)](#function-pointers-CFunction)
  - Pointers
- [Bun.Transpiler](#buntranspiler)
  - [Bun.Transpiler.transformSync](#buntranspilertransformsync)
  - [Bun.Transpiler.transform](#buntranspilertransform)
  - [Bun.Transpiler.scan](#buntranspilerscan)
  - [Bun.Transpiler.scanImports](#buntranspilerscanimports)
- [Bun.peek - read a promise same-tick](#bunpeek---read-a-promise-without-resolving-it)
  - MacOS

Using bun.js - a new JavaScript runtime environment

bun.js focuses on performance, developer experience and compatibility with the JavaScript ecosystem.

  1. ```ts
  2. // http.ts
  3. export default {
  4.   port: 3000,
  5.   fetch(request: Request) {
  6.     return new Response("Hello World");
  7.   },
  8. };

  9. // bun ./http.ts
  10. ```


Measured with http_load_test by running:

  1. ``` sh
  2. ./http_load_test  20 3000
  3. ```

bun.js prefers Web API compatibility instead of designing new APIs when possible. bun.js also implements some Node.js APIs.

- TypeScript & JSX support is built-in, powered by Bun's JavaScript transpiler
- ESM & CommonJS modules are supported (internally, bun.js uses ESM)
- Many npm packages "just work" with bun.js (when they use few/no node APIs)
- tsconfig.json "paths" is natively supported, along with "exports" in package.json
- fs, path, and process from Node are partially implemented
- Web APIs like [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch), [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response), [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) and more are built-in
- [HTMLRewriter](https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/) makes it easy to transform HTML in bun.js
- Starts 4x faster than Node (try it yourself)
- .env files automatically load into process.env and Bun.env
- top level await

The runtime uses JavaScriptCore, the JavaScript engine powering WebKit and Safari. Some web APIs like [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) and [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) directly use Safari's implementation.

cat clone that runs 2x faster than GNU cat for large files on Linux

  1. ``` js
  2. // cat.js
  3. import { resolve } from "path";
  4. import { write, stdout, file, argv } from "bun";

  5. const path = resolve(argv.at(-1));

  6. await write(
  7.   // stdout is a Blob
  8.   stdout,
  9.   // file(path) returns a Blob - https://developer.mozilla.org/en-US/docs/Web/API/Blob
  10.   file(path),
  11. );

  12. // bun ./cat.js ./path-to-file
  13. ```

Server-side render React:

  1. ``` js
  2. // requires Bun v0.1.0 or later
  3. // react-ssr.tsx
  4. import { renderToReadableStream } from "react-dom/server";

  5. const dt = new Intl.DateTimeFormat();

  6. export default {
  7.   port: 3000,
  8.   async fetch(request: Request) {
  9.     return new Response(
  10.       await renderToReadableStream(
  11.         <html>
  12.           <head>
  13.             <title>Hello World</title>
  14.           </head>
  15.           <body>
  16.             <h1>Hello from React!</h1>
  17.             <p>The date is {dt.format(new Date())}</p>
  18.           </body>
  19.         </html>,
  20.       ),
  21.     );
  22.   },
  23. };

  24. // bun react-ssr.tsx
  25. ```

There are some more examples in the examples folder.

PRs adding more examples are very welcome!

Types for bun.js (editor autocomplete)

The best docs right now are the TypeScript types in the [bun-types](https://github.com/oven-sh/bun/tree/main/packages/bun-types) npm package. A docs site is coming soon.

To get autocomplete for bun.js types in your editor,

1. Install the bun-types npm package:

  1. ``` sh
  2. # yarn/npm/pnpm work too, "bun-types" is an ordinary npm package
  3. bun add bun-types
  4. ```

2. Add this to your tsconfig.json or jsconfig.json:

  1. ``` jsonc
  2. {
  3.   "compilerOptions": {
  4.     "lib": ["ESNext"],
  5.     "module": "esnext",
  6.     "target": "esnext",
  7.     "moduleResolution": "node",
  8.     // "bun-types" is the important part
  9.     "types": ["bun-types"]
  10.   }
  11. }
  12. ```

You can also view the types here.

To contribute to the types, head over to oven-sh/bun-types.

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:

  1. ``` js
  2. const blob = Bun.file("input.txt");
  3. await Bun.write("output.txt", blob);
  4. ```

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).

  1. ``` js
  2. // Eventually, this will stream the response to disk but today it buffers
  3. await Bun.write("index.html", await fetch("https://example.com"));
  4. ```

Using bun as a package manager

On Linux, bun install tends to install packages 20x - 100x faster than npm install. On macOS, it’s more like 4x - 80x.

To install packages from package.json:

  1. ``` sh
  2. bun install
  3. ```

To add or remove packages from package.json:

  1. ``` sh
  2. bun remove react
  3. bun add preact
  4. ```

For Linux users: bun install needs Linux Kernel 5.6 or higher to work well

The minimum Linux Kernel version is 5.1. If you're on Linux kernel 5.1 - 5.5, bun install should still work, but HTTP requests will be slow due to a lack of support for io_uring's connect() operation.

If you're using Ubuntu 20.04, here's how to install a newer kernel:

  1. ``` sh
  2. # If this returns a version >= 5.6, you don't need to do anything
  3. uname -r

  4. # Install the official Ubuntu hardware enablement kernel
  5. sudo apt install --install-recommends linux-generic-hwe-20.04
  6. ```

Using bun as a task runner

Instead of waiting 170ms for your npm client to start for each task, you wait 6ms for bun.

To use bun as a task runner, run bun run instead of npm run.

  1. ``` sh
  2. # Instead of "npm run clean"
  3. bun run clean

  4. # This also works
  5. bun clean
  6. ```

Assuming a package.json with a "clean" command in "scripts":

  1. ``` json
  2. {
  3.   "name": "myapp",
  4.   "scripts": {
  5.     "clean": "rm -rf dist out node_modules"
  6.   }
  7. }
  8. ```

Creating a Discord bot with Bun

Application Commands

Application commands are native ways to interact with apps in the Discord client. There are 3 types of commands accessible in different interfaces: the chat input, a message's context menu (top-right menu or right-clicking in a message), and a user's context menu (right-clicking on a user).

To get started you can use the interactions template:

  1. ``` sh
  2. bun create discord-interactions my-interactions-bot
  3. cd my-interactions-bot
  4. ```

If you don't have a Discord bot/application yet, you can create one here (https://discord.com/developers/applications/me).

Invite bot to your server by visiting `https://discord.com/api/oauth2/authorize?client_id=&scope=bot%20applications.commands`

Afterwards you will need to get your bot's token, public key, and application id from the application page and put them into .env.example file

Then you can run the http server that will handle your interactions:

  1. ``` sh
  2. bun install
  3. mv .env.example .env

  4. bun run.js # listening on port 1337
  5. ```

Discord does not accept an insecure HTTP server, so you will need to provide an SSL certificate or put the interactions server behind a secure reverse proxy. For development, you can use ngrok/cloudflare tunnel to expose local ports as secure URL.

Using bun with Next.js

To create a new Next.js app with bun:

  1. ``` sh
  2. bun create next ./app
  3. cd app
  4. bun dev # start dev server
  5. ```

To use an existing Next.js app with bun:

  1. ``` sh
  2. bun add bun-framework-next
  3. echo "framework = 'next'" > bunfig.toml
  4. bun bun # bundle dependencies
  5. bun dev # start dev server
  6. ```

Many of Next.js’ features are supported, but not all.

Here’s what doesn’t work yet:

- getStaticPaths
- same-origin fetch inside of getStaticProps or getServerSideProps
- locales, zones, assetPrefix (workaround: change --origin \"http://localhost:3000/assetPrefixInhere\")
- `next/image` is polyfilled to a regular `` tag.
- proxy and anything else in next.config.js
- API routes, middleware (middleware is easier to support, though! Similar SSR API)
- styled-jsx (technically not Next.js, but often used with it)
- React Server Components

When using Next.js, bun automatically reads configuration from .env.local, .env.development and .env (in that order). process.env.NEXT_PUBLIC_ and process.env.NEXT_ automatically are replaced via --define.

Currently, any time you import new dependencies from node_modules, you will need to re-run bun bun --use next. This will eventually be automatic.

Using bun with single-page apps

In your project folder root (where package.json is):

  1. ``` sh
  2. bun bun ./entry-point-1.js ./entry-point-2.jsx
  3. bun
  4. ```

By default, bun will look for any HTML files in the public directory and serve that. For browsers navigating to the page, the .html file extension is optional in the URL, and index.html will automatically rewrite for the directory.

Here are examples of routing from public/ and how they’re matched:

If public/index.html exists, it becomes the default page instead of a 404 page, unless that pathname has a file extension.

Using bun with Create React App

To create a new React app:

  1. ``` sh
  2. bun create react ./app
  3. cd app
  4. bun dev # start dev server
  5. ```

To use an existing React app:

  1. ``` sh
  2. # To enable React Fast Refresh, ensure it is installed
  3. bun add -d react-refresh

  4. # Generate a bundle for your entry point(s)
  5. bun bun ./src/index.js # jsx, tsx, ts also work. can be multiple files

  6. # Start the dev server
  7. bun dev
  8. ```

From there, bun relies on the filesystem for mapping dev server paths to source files. All URL paths are relative to the project root (where package.json is located).

Here are examples of routing source code file paths:


You do not need to include file extensions in import paths. CommonJS-style import paths without the file extension work.

You can override the public directory by passing --public-dir="path-to-folder".

If no directory is specified and ./public/ doesn’t exist, bun will try ./static/. If ./static/ does not exist, but won’t serve from a public directory. If you pass --public-dir=./ bun will serve from the current directory, but it will check the current directory last instead of first.

Using bun with TypeScript

Transpiling TypeScript with Bun

TypeScript just works. There’s nothing to configure and nothing extra to install. If you import a .ts or .tsx file, bun will transpile it into JavaScript. bun also transpiles node_modules containing .ts or .tsx files. This is powered by bun’s TypeScript transpiler, so it’s fast.

bun also reads tsconfig.json, including baseUrl and paths.

Adding Type Definitions

To get TypeScript working with the global API, add bun-types to your project:

  1. ```sh
  2. bun add -d bun-types
  3. ```

And to the types field in your tsconfig.json:

  1. ``` json
  2. {
  3.   "compilerOptions": {
  4.     "types": ["bun-types"]
  5.   }
  6. }
  7. ```

Not implemented yet

bun is a project with an incredibly large scope and is still in its early days.

You can see Bun's Roadmap, but here are some additional things that are planned:


JS Transpiler == JavaScript Transpiler

TS Transpiler == TypeScript Transpiler

Package manager == bun install
bun.js == bun’s JavaScriptCore integration that executes JavaScript. Similar to how Node.js & Deno embed V8.

Limitations & intended usage

Today, bun is mostly focused on bun.js: the JavaScript runtime.

While you could use bun's bundler & transpiler separately to build for browsers or node, bun doesn't have a minifier or support tree-shaking yet. For production browser builds, you probably should use a tool like esbuild or swc.

Longer-term, bun intends to replace Node.js, Webpack, Babel, yarn, and PostCSS (in production).

Upcoming breaking changes

- Bun's CLI flags will change to better support bun as a JavaScript runtime. They were chosen when bun was just a frontend development tool.
- Bun's bundling format will change to accommodate production browser bundles and on-demand production bundling



bunfig.toml is bun's configuration file.

It lets you load configuration from a file instead of passing flags to the CLI each time. The config file is loaded before CLI arguments are parsed, which means CLI arguments can override them.

Here is an example:

  1. ```toml
  2. # Set a default framework to use
  3. # By default, bun will look for an npm package like `bun-framework-${framework}`, followed by `${framework}`
  4. framework = "next"
  5. logLevel = "debug"

  6. # publicDir = "public"
  7. # external = ["jquery"]

  8. [macros]
  9. # Remap any import like this:
  10. #    import {graphql} from 'react-relay';
  11. # To:
  12. #    import {graphql} from 'macro:bun-macro-relay';
  13. react-relay = { "graphql" = "bun-macro-relay" }

  14. [bundle]
  15. saveTo = "node_modules.bun"
  16. # Don't need this if `framework` is set, but showing it here as an example anyway
  17. entryPoints = ["./app/index.ts"]

  18. [bundle.packages]
  19. # If you're bundling packages that do not actually live in a `node_modules` folder or do not have the full package name in the file path, you can pass this to bundle them anyway
  20. "@bigapp/design-system" = true

  21. [dev]
  22. # Change the default port from 3000 to 5000
  23. # Also inherited by Bun.serve
  24. port = 5000

  25. [define]
  26. # Replace any usage of "process.env.bagel" with the string `lox`.
  27. # The values are parsed as JSON, except single-quoted strings are supported and `'undefined'` becomes `undefined` in JS.
  28. # This will probably change in a future release to be just regular TOML instead. It is a holdover from the CLI argument parsing.
  29. "process.env.bagel" = "'lox'"

  30. [loaders]
  31. # When loading a .bagel file, run the JS parser
  32. ".bagel" = "js"

  33. [debug]
  34. # When navigating to a blob: or src: link, open the file in your editor
  35. # If not, it tries $EDITOR or $VISUAL
  36. # If that still fails, it will try Visual Studio Code, then Sublime Text, then a few others
  37. # This is used by Bun.openInEditor()
  38. editor = "code"

  39. # List of editors:
  40. # - "subl", "sublime"
  41. # - "vscode", "code"
  42. # - "textmate", "mate"
  43. # - "idea"
  44. # - "webstorm"
  45. # - "nvim", "neovim"
  46. # - "vim","vi"
  47. # - "emacs"
  48. # - "atom"
  49. # If you pass it a file path, it will open with the file path instead
  50. # It will recognize non-GUI editors, but I don't think it will work yet
  51. ```

TODO: list each property name


A loader determines how to map imports & file extensions to transforms and output.

Currently, bun implements the following loaders:


Everything else is treated as file. file replaces the import with a URL (or a path).

You can configure which loaders map to which extensions by passing --loaders to bun. For example:

  1. ```sh
  2. bun --loader=.js:js
  3. ```

This will disable JSX transforms for .js files.

CSS in JS (bun dev only)

When importing CSS in JavaScript-like loaders, CSS is treated special.

By default, bun will transform a statement like this:

  1. ``` js
  2. import "../styles/global.css";
  3. ```

When platform is browser

  1. ``` js
  2. globalThis.document?.dispatchEvent(
  3.   new CustomEvent("onimportcss", {
  4.     detail: "http://localhost:3000/styles/globals.css",
  5.   }),
  6. );
  7. ```

An event handler for turning that into a `` is automatically registered when HMR is enabled. That event handler can be turned off either in a framework’s `package.json` or by setting `globalThis["Bun_disableCSSImports"] = true;` in client-side code. Additionally, you can get a list of every .css file imported this way via `globalThis["__BUN"].allImportedStyles`.

When platform is bun

  1. ``` js
  2. //@import url("http://localhost:3000/styles/globals.css");
  3. ```

Additionally, bun exposes an API for SSR/SSG that returns a flat list of URLs to css files imported. That function is Bun.getImportedStyles().

  1. ```ts
  2. // This specifically is for "framework" in package.json when loaded via `bun dev`
  3. // This API needs to be changed somewhat to work more generally with Bun.js
  4. // Initially, you could only use bun.js through `bun dev`
  5. // and this API was created at that time
  6. addEventListener("fetch", async (event: FetchEvent) => {
  7.   let route = Bun.match(event);
  8.   const App = await import("pages/_app");

  9.   // This returns all .css files that were imported in the line above.
  10.   // It’s recursive, so any file that imports a CSS file will be included.
  11.   const appStylesheets = bun.getImportedStyles();

  12.   // ...rest of code
  13. });
  14. ```

This is useful for preventing flash of unstyled content.

CSS Loader

bun bundles .css files imported via @import into a single file. It doesn’t autoprefix or minify CSS today. Multiple .css files imported in one JavaScript file will _not_ be bundled into one file. You’ll have to import those from a .css file.

This input:

  1. ```css
  2. @import url("./hi.css");
  3. @import url("./hello.css");
  4. @import url("./yo.css");
  5. ```


  1. ```css
  2. /* hi.css */
  3. /* ...contents of hi.css */
  4. /* hello.css */
  5. /* ...contents of hello.css */
  6. /* yo.css */
  7. /* ...contents of yo.css */
  8. ```

CSS runtime

To support hot CSS reloading, bun inserts @supports annotations into CSS that tag which files a stylesheet is composed of. Browsers ignore this, so it doesn’t impact styles.

By default, bun’s runtime code automatically listens to `onimportcss` and will insert the `event.detail` into a `` if there is no existing `link` tag with that stylesheet. That’s how bun’s equivalent of `style-loader` works.



This will soon have breaking changes. It was designed when Bun was mostly a dev server and not a JavaScript runtime.

Frameworks preconfigure bun to enable developers to use bun with their existing tooling.

Frameworks are configured via the framework object in the package.json of the framework (not in the application’s package.json):

Here is an example:

  1. ``` json
  2. {
  3.   "name": "bun-framework-next",
  4.   "version": "0.0.0-18",
  5.   "description": ,
  6.   "framework": {
  7.     "displayName": "Next.js",
  8.     "static": "public",
  9.     "assetPrefix": "_next/",
  10.     "router": {
  11.       "dir": ["pages", "src/pages"],
  12.       "extensions": [".js", ".ts", ".tsx", ".jsx"]
  13.     },
  14.     "css": "onimportcss",
  15.     "development": {
  16.       "client": "client.development.tsx",
  17.       "fallback": "fallback.development.tsx",
  18.       "server": "server.development.tsx",
  19.       "css": "onimportcss",
  20.       "define": {
  21.         "client": {
  22.           ".env": "NEXT_PUBLIC_",
  23.           "defaults": {
  24.             "process.env.__NEXT_TRAILING_SLASH": "false",
  25.             "process.env.NODE_ENV": "\"development\",
  26.             "process.env.__NEXT_ROUTER_BASEPATH": "''",
  27.             "process.env.__NEXT_SCROLL_RESTORATION": "false",
  28.             "process.env.__NEXT_I18N_SUPPORT": "false",
  29.             "process.env.__NEXT_HAS_REWRITES": "false",
  30.             "process.env.__NEXT_ANALYTICS_ID": "null",
  31.             "process.env.__NEXT_OPTIMIZE_CSS": "false",
  32.             "process.env.__NEXT_CROSS_ORIGIN": "''",
  33.             "process.env.__NEXT_STRICT_MODE": "false",
  34.             "process.env.__NEXT_IMAGE_OPTS": "null"
  35.           }
  36.         },
  37.         "server": {
  38.           ".env": "NEXT_",
  39.           "defaults": {
  40.             "process.env.__NEXT_TRAILING_SLASH": "false",
  41.             "process.env.__NEXT_OPTIMIZE_FONTS": "false",
  42.             "process.env.NODE_ENV": "\"development\",
  43.             "process.env.__NEXT_OPTIMIZE_IMAGES": "false",
  44.             "process.env.__NEXT_OPTIMIZE_CSS": "false",
  45.             "process.env.__NEXT_ROUTER_BASEPATH": "''",
  46.             "process.env.__NEXT_SCROLL_RESTORATION": "false",
  47.             "process.env.__NEXT_I18N_SUPPORT": "false",
  48.             "process.env.__NEXT_HAS_REWRITES": "false",
  49.             "process.env.__NEXT_ANALYTICS_ID": "null",
  50.             "process.env.__NEXT_CROSS_ORIGIN": "''",
  51.             "process.env.__NEXT_STRICT_MODE": "false",
  52.             "process.env.__NEXT_IMAGE_OPTS": "null",
  53.             "global": "globalThis",
  54.             "window": "undefined"
  55.           }
  56.         }
  57.       }
  58.     }
  59.   }
  60. }
  61. ```

Here are type definitions:

  1. ```ts
  2. type Framework = Environment & {
  3.   // This changes what’s printed in the console on load
  4.   displayName?: string;

  5.   // This allows a prefix to be added (and ignored) to requests.
  6.   // Useful for integrating an existing framework that expects internal routes to have a prefix
  7.   // e.g. "_next"
  8.   assetPrefix?: string;

  9.   development?: Environment;
  10.   production?: Environment;

  11.   // The directory used for serving unmodified assets like fonts and images
  12.   // Defaults to "public" if exists, else "static", else disabled.
  13.   static?: string;

  14.   // "onimportcss" disables the automatic "onimportcss" feature
  15.   // If the framework does routing, you may want to handle CSS manually
  16.   // "facade" removes CSS imports from JavaScript files,
  17.   //    and replaces an imported object with a proxy that mimics CSS module support without doing any class renaming.
  18.   css?: "onimportcss" | "facade";

  19.   // bun’s filesystem router
  20.   router?: Router;
  21. };

  22. type Define = {
  23.   // By passing ".env", bun will automatically load .env.local, .env.development, and .env if exists in the project root
  24.   //    (in addition to the processes’ environment variables)
  25.   // When "*", all environment variables will be automatically injected into the JavaScript loader
  26.   // When a string like "NEXT_PUBLIC_", only environment variables starting with that prefix will be injected

  27.   ".env": string | "*";

  28.   // These environment variables will be injected into the JavaScript loader
  29.   // These are the equivalent of Webpack’s resolve.alias and esbuild’s --define.
  30.   // Values are parsed as JSON, so they must be valid JSON. The only exception is '' is a valid string, to simplify writing stringified JSON in JSON.
  31.   // If not set, `process.env.NODE_ENV` will be transformed into "development".
  32.   defaults: Record<string, string>;
  33. };

  34. type Environment = {
  35.   // This is a wrapper for the client-side entry point for a route.
  36.   // This allows frameworks to run initialization code on pages.
  37.   client: string;
  38.   // This is a wrapper for the server-side entry point for a route.
  39.   // This allows frameworks to run initialization code on pages.
  40.   server: string;
  41.   // This runs when "server" code fails to load due to an exception.
  42.   fallback: string;

  43.   // This is how environment variables and .env is configured.
  44.   define?: Define;
  45. };

  46. // bun’s filesystem router
  47. // Currently, bun supports pages by either an absolute match or a parameter match.
  48. // pages/index.tsx will be executed on navigation to "/" and "/index"
  49. // pages/posts/[id].tsx will be executed on navigation to "/posts/123"
  50. // Routes & parameters are automatically passed to `fallback` and `server`.
  51. type Router = {
  52.   // This determines the folder to look for pages
  53.   dir: string[];

  54.   // These are the allowed file extensions for pages.
  55.   extensions?: string[];
  56. };
  57. ```

To use a framework, you pass bun bun --use package-name.

Your framework’s package.json name should start with bun-framework-. This is so that people can type something like bun bun --use next and it will check bun-framework-next first. This is similar to how Babel plugins tend to start with babel-plugin-.

For developing frameworks, you can also do bun bun --use ./relative-path-to-framework.

If you’re interested in adding a framework integration, please reach out. There’s a lot here, and it’s not entirely documented yet.


bun not running on an M1 (or Apple Silicon)

If you see a message like this

[1] 28447 killed bun create next ./test

It most likely means you’re running bun’s x64 version on Apple Silicon. This happens if bun is running via Rosetta. Rosetta is unable to emulate AVX2 instructions, which bun indirectly uses.

The fix is to ensure you installed a version of bun built for Apple Silicon.

error: Unexpected

If you see an error like this:


It usually means the max number of open file descriptors is being explicitly set to a low number. By default, bun requests the max number of file descriptors available (which on macOS, is something like 32,000). But, if you previously ran into ulimit issues with, e.g., Chokidar, someone on The Internet may have advised you to run ulimit -n 8096.

That advice unfortunately lowers the hard limit to 8096. This can be a problem in large repositories or projects with lots of dependencies. Chokidar (and other watchers) don’t seem to call setrlimit, which means they’re reliant on the (much lower) soft limit.

To fix this issue:

1. Remove any scripts that call ulimit -n and restart your shell.
2. Try again, and if the error still occurs, try setting ulimit -n to an absurdly high number, such as ulimit -n 2147483646
3. Try again, and if that still doesn’t fix it, open an issue

Unzip is required

Unzip is required to install bun on Linux. You can use one of the following commands to install unzip:

Debian / Ubuntu / Mint

  1. ```sh
  2. sudo apt install unzip
  3. ```

RedHat / CentOS / Fedora

  1. ```sh
  2. sudo dnf install unzip
  3. ```

Arch / Manjaro

  1. ```sh
  2. sudo pacman -S unzip
  3. ```


  1. ```sh
  2. sudo zypper install unzip
  3. ```

bun install is stuck

Please run bun install --verbose 2> logs.txt and send them to me in bun's discord. If you're on Linux, it would also be helpful if you run sudo perf trace bun install --silent and attach the logs.


bun install

bun install is a fast package manager & npm client.

bun install can be configured via bunfig.toml, environment variables, and CLI flags.

Configuring bun install with bunfig.toml

bunfig.toml is searched for in the following paths on bun install, bun remove, and bun add:

1. $XDG_CONFIG_HOME/.bunfig.toml or $HOME/.bunfig.toml
2. ./bunfig.toml

If both are found, the results are merged together.

Configuring with bunfig.toml is optional. bun tries to be zero configuration in general, but that's not always possible.

  1. ```toml
  2. # Using scoped packages with bun install
  3. [install.scopes]

  4. # Scope name      The value can be a URL string or an object
  5. "@mybigcompany" = { token = "123456", url = "https://registry.mybigcompany.com" }
  6. # URL is optional and fallsback to the default registry

  7. # The "@" in the scope is optional
  8. mybigcompany2 = { token = "123456" }

  9. # Environment variables can be referenced as a string that starts with $ and it will be replaced
  10. mybigcompany3 = { token = "$npm_config_token" }

  11. # Setting username and password turns it into a Basic Auth header by taking base64("username:password")
  12. mybigcompany4 = { username = "myusername", password = "$npm_config_password", url = "https://registry.yarnpkg.com/" }
  13. # You can set username and password in the registry URL. This is the same as above.
  14. mybigcompany5 = "https://username:password@registry.yarnpkg.com/"

  15. # You can set a token for a registry URL:
  16. mybigcompany6 = "https://:$NPM_CONFIG_TOKEN@registry.yarnpkg.com/"

  17. [install]
  18. # Default registry
  19. # can be a URL string or an object
  20. registry = "https://registry.yarnpkg.com/"
  21. # as an object
  22. #registry = { url = "https://registry.yarnpkg.com/", token = "123456" }

  23. # Install for production? This is the equivalent to the "--production" CLI argument
  24. production = false

  25. # Don't actually install
  26. dryRun = true

  27. # Install optionalDependencies (default: true)
  28. optional = true

  29. # Install local devDependencies (default: true)
  30. dev = true

  31. # Install peerDependencies (default: false)
  32. peer = false

  33. # When using `bun install -g`, install packages here
  34. globalDir = "~/.bun/install/global"

  35. # When using `bun install -g`, link package bins here
  36. globalBinDir = "~/.bun/bin"

  37. # cache-related configuration
  38. [install.cache]
  39. # The directory to use for the cache
  40. dir = "~/.bun/install/cache"

  41. # Don't load from the global cache.
  42. # Note: bun may still write to node_modules/.cache
  43. disable = false

  44. # Always resolve the latest versions from the registry
  45. disableManifest = false

  46. # Lockfile-related configuration
  47. [install.lockfile]

  48. # Print a yarn v1 lockfile
  49. # Note: it does not load the lockfile, it just converts bun.lockb into a yarn.lock
  50. print = "yarn"

  51. # Path to read bun.lockb from
  52. path = "bun.lockb"

  53. # Path to save bun.lockb to
  54. savePath = "bun.lockb"

  55. # Save the lockfile to disk
  56. save = true

  57. ```

If it's easier to read as TypeScript types:

  1. ```ts
  2. export interface Root {
  3.   install: Install;
  4. }

  5. export interface Install {
  6.   scopes: Scopes;
  7.   registry: Registry;
  8.   production: boolean;
  9.   dryRun: boolean;
  10.   optional: boolean;
  11.   dev: boolean;
  12.   peer: boolean;
  13.   globalDir: string;
  14.   globalBinDir: string;
  15.   cache: Cache;
  16.   lockfile: Lockfile;
  17.   logLevel: "debug" | "error" | "warn";
  18. }

  19. type Registry =
  20.   | string
  21.   | {
  22.       url?: string;
  23.       token?: string;
  24.       username?: string;
  25.       password?: string;
  26.     };

  27. type Scopes = Record<string, Registry>;

  28. export interface Cache {
  29.   dir: string;
  30.   disable: boolean;
  31.   disableManifest: boolean;
  32. }

  33. export interface Lockfile {
  34.   print?: "yarn";
  35.   path: string;
  36.   savePath: string;
  37.   save: boolean;
  38. }
  39. ```

Configuring with environment variables

Environment variables have a higher priority than bunfig.toml.


bun always tries to use the fastest available installation method for the target platform. On macOS, that’s clonefile and on Linux, that’s hardlink. You can change which installation method is used with the --backend flag. When unavailable or on error, clonefile and hardlink fallsback to a platform-specific implementation of copying files.

bun stores installed packages from npm in ~/.bun/install/cache/${name}@${version}. Note that if the semver version has a build or a pre tag, it is replaced with a hash of that value instead. This is to reduce the chances of errors from long file paths, but unfortunately complicates figuring out where a package was installed on disk.

When the node_modules folder exists, before installing, bun checks if the "name" and "version" in package/package.json in the expected node_modules folder matches the expected name and version. This is how it determines whether it should install. It uses a custom JSON parser which stops parsing as soon as it finds "name" and "version".

When a bun.lockb doesn’t exist or package.json has changed dependencies, tarballs are downloaded & extracted eagerly while resolving.

When a bun.lockb exists and package.json hasn’t changed, bun downloads missing dependencies lazily. If the package with a matching name & version already exists in the expected location within node_modules, bun won’t attempt to download the tarball.

Platform-specific dependencies?

bun stores normalized cpu and os values from npm in the lockfile, along with the resolved packages. It skips downloading, extracting, and installing packages disabled for the current target at runtime. This means the lockfile won’t change between platforms/architectures even if the packages ultimately installed do change.

Peer dependencies?

Peer dependencies are handled similarly to yarn. bun install does not automatically install peer dependencies and will try to choose an existing dependency.


bun.lockb is bun’s binary lockfile format.

Why is it binary?

In a word: Performance. bun’s lockfile saves & loads incredibly quickly, and saves a lot more data than what is typically inside lockfiles.

How do I inspect it?

For now, the easiest thing is to run bun install -y. That prints a Yarn v1-style yarn.lock file.

What does the lockfile store?

Packages, metadata for those packages, the hoisted install order, dependencies for each package, what packages those dependencies resolved to, an integrity hash (if available), what each package was resolved to and which version (or equivalent).

Why is it fast?

It uses linear arrays for all data. Packages are referenced by an auto-incrementing integer ID or a hash of the package name. Strings longer than 8 characters are de-duplicated. Prior to saving on disk, the lockfile is garbage-collected & made deterministic by walking the package tree and cloning the packages in dependency order.


To delete the cache:

  1. ``` sh
  2. rm -rf ~/.bun/install/cache
  3. ```

Platform-specific backends

bun install uses different system calls to install dependencies depending on the platform. This is a performance optimization. You can force a specific backend with the --backend flag.

hardlink is the default backend on Linux. Benchmarking showed it to be the fastest on Linux.

  1. ``` sh
  2. rm -rf node_modules
  3. bun install --backend hardlink
  4. ```

clonefile is the default backend on macOS. Benchmarking showed it to be the fastest on macOS. It is only available on macOS.

  1. ``` sh
  2. rm -rf node_modules
  3. bun install --backend clonefile
  4. ```

clonefile_each_dir is similar to clonefile, except it clones each file individually per directory. It is only available on macOS and tends to perform slower than clonefile. Unlike clonefile, this does not recursively clone subdirectories in one system call.

  1. ``` sh
  2. rm -rf node_modules
  3. bun install --backend clonefile_each_dir
  4. ```

copyfile is the fallback used when any of the above fail, and is the slowest. on macOS, it uses fcopyfile() and on linux it uses copy_file_range().

  1. ``` sh
  2. rm -rf node_modules
  3. bun install --backend copyfile
  4. ```

symlink is typically only used for file: dependencies (and eventually link:) internally. To prevent infinite loops, it skips symlinking the node_modules folder.

If you install with --backend=symlink, Node.js won't resolve node_modules of dependencies unless each dependency has it's own node_modules folder or you pass --preserve-symlinks to node. See [Node.js documentation on --preserve-symlinks](https://nodejs.org/api/cli.html#--preserve-symlinks).

  1. ``` sh
  2. rm -rf node_modules
  3. bun install --backend symlink

  4. # https://nodejs.org/api/cli.html#--preserve-symlinks
  5. node --preserve-symlinks ./my-file.js
  6. ```

bun's runtime does not currently expose an equivalent of --preserve-symlinks, though the code for it does exist.

npm registry metadata

bun uses a binary format for caching NPM registry responses. This loads much faster than JSON and tends to be smaller on disk.
You will see these files in ~/.bun/install/cache/*.npm. The filename pattern is ${hash(packageName)}.npm. It’s a hash so that extra directories don’t need to be created for scoped packages.

bun’s usage of Cache-Control ignores Age. This improves performance, but means bun may be about 5 minutes out of date to receive the latest package version metadata from npm.

bun run

bun run is a fast package.json script runner. Instead of waiting 170ms for your npm client to start every time, you wait 6ms for bun.

By default, bun run prints the script that will be invoked:

  1. ``` sh
  2. bun run clean
  3. $ rm -rf node_modules/.cache dist
  4. ```

You can disable that with --silent

  1. ``` sh
  2. bun run --silent clean
  3. ```

bun run ${script-name} runs the equivalent of npm run script-name. For example, bun run dev runs the dev script in package.json, which may sometimes spin up non-bun processes.

bun run ${javascript-file.js} will run it with bun, as long as the file doesn't have a node shebang.

To print a list of scripts, bun run without additional args:

  1. ``` sh
  2. # This command
  3. bun run

  4. # Prints this
  5. hello-create-react-app scripts:

  6. bun run start
  7. react-scripts start

  8. bun run build
  9. react-scripts build

  10. bun run test
  11. react-scripts test

  12. bun run eject
  13. react-scripts eject

  14. 4 scripts
  15. ```

bun run automatically loads environment variables from .env into the shell/task. .env files are loaded with the same priority as the rest of bun, so that means:

1. .env.local is first
2. if ($NODE_ENV === "production") .env.production else .env.development
3. .env

If something is unexpected there, you can run bun run env to get a list of environment variables.

The default shell it uses is bash, but if that’s not found, it tries sh and if still not found, it tries zsh. This is not configurable right now, but if you care, file an issue.

bun run automatically adds any parent node_modules/.bin to $PATH and if no scripts match, it will load that binary instead. That means you can run executables from packages, too.

  1. ``` sh
  2. # If you use Relay
  3. bun run relay-compiler

  4. # You can also do this, but:
  5. # - It will only lookup packages in `node_modules/.bin` instead of `$PATH`
  6. # - It will start buns dev server if the script name doesnt exist (`bun` starts the dev server by default)
  7. bun relay-compiler
  8. ```

To pass additional flags through to the task or executable, there are two ways:

  1. ``` sh
  2. # Explicit: include "--" and anything after will be added. This is the recommended way because it is more reliable.
  3. bun run relay-compiler -- -help

  4. # Implicit: if you do not include "--", anything *after* the script name will be passed through
  5. # bun flags are parsed first, which means e.g. `bun run relay-compiler --help` will print buns help instead of relay-compilers help.
  6. bun run relay-compiler --schema foo.graphql
  7. ```

bun run supports lifecycle hooks like post${task} and pre{task}. If they exist, they will run, matching the behavior of npm clients. If the pre${task} fails, the next task will not be run. There is currently no flag to skip these lifecycle tasks if they exist, if you want that file an issue.

bun --hot

bun --hot enables hot reloading of code in Bun's JavaScript runtime. This is a very experimental feature available in Bun v0.2.0.

Unlike file watchers like nodemon, bun --hot can keep stateful objects like the HTTP server running.

Bun v0.2.0

Screen Recording 2022-10-06 at 2 36 06 AM

To use it with Bun's HTTP server (automatic):


  1. ```ts
  2. // The global object is preserved across code reloads
  3. // You can use it to store state, for now until Bun implements import.meta.hot.
  4. const reloadCount = globalThis.reloadCount || 0;
  5. globalThis.reloadCount = reloadCount + 1;

  6. export default {
  7.   fetch(req: Request) {
  8.     return new Response(`Code reloaded ${reloadCount} times`, {
  9.       headers: { "content-type": "text/plain" },
  10.     });
  11.   },
  12. };
  13. ```

Then, run:

  1. ``` sh
  2. bun --hot server.ts
  3. ```

You can also use bun run:

  1. ``` sh
  2. bun run --hot server.ts
  3. ```

To use it manually:

  1. ```ts
  2. // The global object is preserved across code reloads
  3. // You can use it to store state, for now until Bun implements import.meta.hot.
  4. const reloadCount = globalThis.reloadCount || 0;
  5. globalThis.reloadCount = reloadCount + 1;

  6. const reloadServer = (globalThis.reloadServer ||= (() => {
  7.   let server;
  8.   return (handler) => {
  9.     if (server) {
  10.       // call `server.reload` to reload the server
  11.       server.reload(handler);
  12.     } else {
  13.       server = Bun.serve(handler);
  14.     }
  15.     return server;
  16.   };
  17. })());

  18. const handler = {
  19.   fetch(req: Request) {
  20.     return new Response(`Code reloaded ${reloadCount} times`, {
  21.       headers: { "content-type": "text/plain" },
  22.     });
  23.   },
  24. };

  25. reloadServer(handler);
  26. ```

In a future version of Bun, support for Vite's import.meta.hot is planned to enable better lifecycle management for hot reloading and to align with the ecosystem.

How bun --hot works

bun --hot monitors imported files for changes and reloads them. It does not monitor files that are not imported and it does not monitor node_modules.

On reload, it resets the internal require cache and ES module registry (Loader.registry).


- It runs the garbage collector synchronously (to minimize memory leaks, at the cost of runtime performance)
- Bun re-transpiles all of your code from scratch (including sourcemaps)
- JavaScriptCore (the engine) re-evaluates the code.

Traditional file watchers restart the entire process which means that HTTP servers and other stateful objects are lost. bun --hot does not restart the process, so it preserves _some_ state across reloads to be less intrusive.

This implementation isn't particularly optimized. It re-transpiles files that haven't changed. It makes no attempt at incremental compilation. It's a starting point.

bun create

bun create is a fast way to create a new project from a template.

At the time of writing, bun create react app runs ~11x faster on my local computer than yarn create react-app app. bun create currently does no caching (though your npm client does)


Create a new Next.js project:

  1. ``` sh
  2. bun create next ./app
  3. ```

Create a new React project:

  1. ``` sh
  2. bun create react ./app
  3. ```

Create from a GitHub repo:

  1. ``` sh
  2. bun create ahfarmer/calculator ./app
  3. ```

To see a list of templates, run:

  1. ``` sh
  2. bun create
  3. ```


  1. ``` sh
  2. bun create github-user/repo-name destination
  3. bun create local-example-or-remote-example destination
  4. bun create /absolute/path/to-template-folder destination
  5. bun create https://github.com/github-user/repo-name destination
  6. bun create github.com/github-user/repo-name destination
  7. ```

Note: you don’t need bun create to use bun. You don’t need any configuration at all. This command exists to make it a little easier.

Local templates

If you have your own boilerplate you prefer using, copy it into $HOME/.bun-create/my-boilerplate-name.

Before checking bun’s templates on npmjs, bun create checks for a local folder matching the input in:

- $HOME/.bun-create/
- $(pwd)/.bun-create/

If a folder exists in any of those folders with the input, bun will use that instead of a remote template.

To create a local template, run:

  1. ``` sh
  2. mkdir -p $HOME/.bun-create/new-template-name
  3. echo '{"name":"new-template-name"}' > $HOME/.bun-create/new-template-name/package.json
  4. ```

This lets you run:

  1. ``` sh
  2. bun create new-template-name ./app
  3. ```

Now your new template should appear when you run:

  1. ``` sh
  2. bun create
  3. ```

Warning: unlike with remote templates, bun will delete the entire destination folder if it already exists.




By default, bun create will cancel if there are existing files it would overwrite and it's a remote template. You can pass --force to disable this behavior.

Publishing a new template

Clone https://github.com/bun-community/create-templates/ and create a new folder in root directory with your new template. Thepackage.json must have a name that starts with @bun-examples/. Do not worry about publishing it, that will happen automatically after the PR is merged.

Make sure to include a .gitignore that includes node_modules so that node_modules aren’t checked in to git when people download the template.

Testing your new template

To test your new template, add it as a local template or pass the absolute path.

  1. ``` sh
  2. bun create /path/to/my/new/template destination-dir
  3. ```

Warning: This will always delete everything in destination-dir.


The bun-create section of package.json is automatically removed from the package.json on disk. This lets you add create-only steps without waiting for an extra package to install.

There are currently three options:

- postinstall
- preinstall
- start (customize the displayed start command)

They can be an array of strings or one string. An array of steps will be executed in order.

Here is an example:

  1. ``` json
  2. {
  3.   "name": "@bun-examples/next",
  4.   "version": "0.0.31",
  5.   "main": "index.js",
  6.   "dependencies": {
  7.     "next": "11.1.2",
  8.     "react": "^17.0.2",
  9.     "react-dom": "^17.0.2",
  10.     "react-is": "^17.0.2"
  11.   },
  12.   "devDependencies": {
  13.     "@types/react": "^17.0.19",
  14.     "bun-framework-next": "^0.0.0-21",
  15.     "typescript": "^4.3.5"
  16.   },
  17.   "bun-create": {
  18.     "postinstall": ["bun bun --use next"],
  19.     "start": "bun run echo 'Hello world!'"
  20.   }
  21. }
  22. ```

By default, all commands run inside the environment exposed by the auto-detected npm client. This incurs a significant performance penalty, something like 150ms spent waiting for the npm client to start on each invocation.

Any command that starts with "bun " will be run without npm, relying on the first bun binary in $PATH.

How bun create works

When you run bun create ${template} ${destination}, here’s what happens:

IF remote template

1. GET registry.npmjs.org/@bun-examples/${template}/latest and parse it
2. GET registry.npmjs.org/@bun-examples/${template}/-/${template}-${latestVersion}.tgz
3. Decompress & extract ${template}-${latestVersion}.tgz into ${destination}

   - If there are files that would overwrite, warn and exit unless --force is passed

IF GitHub repo

1. Download the tarball from GitHub’s API
2. Decompress & extract into ${destination}

   - If there are files that would overwrite, warn and exit unless --force is passed

ELSE IF local template

1. Open local template folder
2. Delete destination directory recursively
3. Copy files recursively using the fastest system calls available (on macOS fcopyfile and Linux, copy_file_range). Do not copy or traverse into node_modules folder if exists (this alone makes it faster than cp)

4. Parse the `