bun build
CLI command or the Bun.build()
JavaScript API.
At a Glance
- JS API:
await Bun.build({ entrypoints, outdir })
- CLI:
bun build <entry> --outdir ./out
- Watch:
--watch
for incremental rebuilds - Targets:
--target browser|bun|node
- Formats:
--format esm|cjs|iife
(experimental for cjs/iife)
- JavaScript
- CLI

Why bundle?
The bundler is a key piece of infrastructure in the JavaScript ecosystem. As a brief overview of why bundling is so important:- Reducing HTTP requests. A single package in
node_modules
may consist of hundreds of files, and large applications may have dozens of such dependencies. Loading each of these files with a separate HTTP request becomes untenable very quickly, so bundlers are used to convert our application source code into a smaller number of self-contained “bundles” that can be loaded with a single request. - Code transforms. Modern apps are commonly built with languages or tools like TypeScript, JSX, and CSS modules, all of which must be converted into plain JavaScript and CSS before they can be consumed by a browser. The bundler is the natural place to configure these transformations.
- Framework features. Frameworks rely on bundler plugins & code transformations to implement common patterns like file-system routing, client-server code co-location (think
getServerSideProps
or Remix loaders), and server components. - Full-stack Applications. Bun’s bundler can handle both server and client code in a single command, enabling optimized production builds and single-file executables. With build-time HTML imports, you can bundle your entire application — frontend assets and backend server — into a single deployable unit.
The Bun bundler is not intended to replace
tsc
for typechecking or generating type declarations.Basic example
Let’s build our first bundle. You have the following two files, which implement a simple client-side rendered React app.index.tsx
is the “entrypoint” to our application. Commonly, this will be a script that performs some side effect, like starting a server or—in this case—initializing a React root. Because we’re using TypeScript & JSX, we need to bundle our code before it can be sent to the browser.
To create our bundle:
entrypoints
, Bun will generate a new bundle. This bundle will be written to disk in the ./out
directory (as resolved from the current working directory). After running the build, the file system looks like this:
file system
out/index.js
will look something like this:
Watch mode
Like the runtime and test runner, the bundler supports watch mode natively.terminal
Content types
Like the Bun runtime, the bundler supports an array of file types out of the box. The following table breaks down the bundler’s set of standard “loaders”. Refer to Bundler > File types for full documentation.Extensions | Details |
---|---|
.js .jsx .cjs .mjs .mts .cts .ts .tsx | Uses Bun’s built-in transpiler to parse the file and transpile TypeScript/JSX syntax to vanilla JavaScript. The bundler executes a set of default transforms including dead code elimination and tree shaking. At the moment Bun does not attempt to down-convert syntax; if you use recently ECMAScript syntax, that will be reflected in the bundled code. |
.json | JSON files are parsed and inlined into the bundle as a JavaScript object.js<br/>import pkg from "./package.json";<br/>pkg.name; // => "my-package"<br/> |
.toml | TOML files are parsed and inlined into the bundle as a JavaScript object.js<br/>import config from "./bunfig.toml";<br/>config.logLevel; // => "debug"<br/> |
.txt | The contents of the text file are read and inlined into the bundle as a string.js<br/>import contents from "./file.txt";<br/>console.log(contents); // => "Hello, world!"<br/> |
.node .wasm | These files are supported by the Bun runtime, but during bundling they are treated as assets. |
Assets
If the bundler encounters an import with an unrecognized extension, it treats the imported file as an external file. The referenced file is copied as-is intooutdir
, and the import is resolved as a path to the file.
naming
and publicPath
.
Refer to the Bundler > Loaders page for more complete documentation on
the file loader.
Plugins
The behavior described in this table can be overridden or extended with plugins. Refer to the Bundler > Loaders page for complete documentation.API
entrypoints
An array of paths corresponding to the entrypoints of our application. One bundle will be generated for each entrypoint.- JavaScript
- CLI
outdir
The directory where output files will be written.- JavaScript
- CLI
outdir
is not passed to the JavaScript API, bundled code will not be written to disk. Bundled files are returned in an array of BuildArtifact
objects. These objects are Blobs with extra properties; see Outputs for complete documentation.
outdir
is set, the path
property on a BuildArtifact
will be the absolute path to where it was written to.
target
The intended execution environment for the bundle.- JavaScript
- CLI
browser
Default. For generating bundles that are intended for execution by a browser. Prioritizes the
"browser"
export condition when resolving imports. Importing any built-in modules, like
node:events
or node:path
will work, but calling some functions, like fs.readFile
will not
work.bun
For generating bundles that are intended to be run by the Bun runtime. In many cases, it isn’t necessary to bundle server-side code; you can directly execute the source code without modification. However, bundling your server code can reduce startup times and improve running performance. This is the target to use for building full-stack applications with build-time HTML imports, where both server and client code are bundled together.All bundles generated with
target: "bun"
are marked with a special // @bun
pragma, which indicates to the Bun runtime that there’s no need to re-transpile the file before execution.If any entrypoints contains a Bun shebang (#!/usr/bin/env bun
) the bundler will default to target: "bun"
instead of "browser"
.When using target: "bun"
and format: "cjs"
together, the // @bun @bun-cjs
pragma is added and the CommonJS wrapper function is not compatible with Node.js.node
For generating bundles that are intended to be run by Node.js. Prioritizes the
"node"
export
condition when resolving imports, and outputs .mjs
. In the future, this will automatically
polyfill the Bun global and other built-in bun:*
modules, though this is not yet implemented.format
Specifies the module format to be used in the generated bundles. Bun defaults to"esm"
, and provides experimental support for "cjs"
and "iife"
.
format: “esm” - ES Module
This is the default format, which supports ES Module syntax including top-level await,import.meta
, and more.
- JavaScript
- CLI
format
to "esm"
and make sure your <script type="module">
tag has type="module"
set.
format: “cjs” - CommonJS
To build a CommonJS module, setformat
to "cjs"
. When choosing "cjs"
, the default target changes from "browser"
(esm) to "node"
(cjs). CommonJS modules transpiled with format: "cjs"
, target: "node"
can be executed in both Bun and Node.js (assuming the APIs in use are supported by both).
- JavaScript
- CLI
format: “iife” - IIFE
TODO: document IIFE once we support globalNames.jsx
Configure JSX transform behavior. Allows fine-grained control over how JSX is compiled.
Classic runtime example (uses factory
and fragment
):
importSource
):
splitting
Whether to enable code splitting.- JavaScript
- CLI
true
, the bundler will enable code splitting. When multiple entrypoints both import the same file, module, or set of files/modules, it’s often useful to split the shared code into a separate bundle. This shared bundle is known as a chunk. Consider the following files:
entry-a.ts
and entry-b.ts
with code-splitting enabled:
- JavaScript
- CLI
file system
chunk-2fce6291bf86559d.js
file contains the shared code. To avoid collisions, the file name automatically includes a content hash by default. This can be customized with naming
.
plugins
A list of plugins to use during bundling.env
Controls how environment variables are handled during bundling. Internally, this usesdefine
to inject environment variables into the bundle, but makes it easier to specify the environment variables to inject.
env: “inline”
Injects environment variables into the bundled output by convertingprocess.env.FOO
references to string literals containing the actual environment variable values.
- JavaScript
- CLI
env: “PUBLIC_*” (prefix)
Inlines environment variables matching the given prefix (the part before the*
character), replacing process.env.FOO
with the actual environment variable value. This is useful for selectively inlining environment variables for things like public-facing URLs or client-side tokens, without worrying about injecting private credentials into output bundles.
- JavaScript
- CLI
terminal
env: “disable”
Disables environment variable injection entirely.sourcemap
Specifies the type of sourcemap to generate.- JavaScript
- CLI
Value | Description |
---|---|
"none" | Default. No sourcemap is generated. |
"linked" | A separate *.js.map file is created alongside each *.js bundle using a //# sourceMappingURL comment to link the two. Requires --outdir to be set. The base URL of this can be customized with --public-path .js<br/>// <bundled code here><br/><br/>//# sourceMappingURL=bundle.js.map<br/> |
"external" | A separate *.js.map file is created alongside each *.js bundle without inserting a //# sourceMappingURL comment.Generated bundles contain a debug id that can be used to associate a bundle with its corresponding sourcemap. This debugId is added as a comment at the bottom of the file.js<br/>// <generated bundle code><br/><br/>//# debugId=<DEBUG ID><br/> |
"inline" | A sourcemap is generated and appended to the end of the generated bundle as a base64 payload.js<br/>// <bundled code here><br/><br/>//# sourceMappingURL=data:application/json;base64,<encoded sourcemap here><br/> |
*.js.map
sourcemap will be a JSON file containing an equivalent debugId
property.
minify
Whether to enable minification. Defaultfalse
.
When targeting
bun
, identifiers will be minified by default.- JavaScript
- CLI
- JavaScript
- CLI
external
A list of import paths to consider external. Defaults to[]
.
- JavaScript
- CLI
index.tsx
would generate a bundle containing the entire source code of the “zod” package. If instead, we want to leave the import statement as-is, we can mark it as external:
- JavaScript
- CLI
*
:
- JavaScript
- CLI
packages
Control whether package dependencies are included to bundle or not. Possible values:bundle
(default), external
. Bun treats any import which path do not start with .
, ..
or /
as package.
- JavaScript
- CLI
naming
Customizes the generated file names. Defaults to./[dir]/[name].[ext]
.
- JavaScript
- CLI
file system
file system
naming
field. This field accepts a template string that is used to generate the filenames for all bundles corresponding to entrypoints. where the following tokens are replaced with their corresponding values:
[name]
- The name of the entrypoint file, without the extension.[ext]
- The extension of the generated bundle.[hash]
- A hash of the bundle contents.[dir]
- The relative path from the project root to the parent directory of the source file.
Token | [name] | [ext] | [hash] | [dir] |
---|---|---|---|---|
./index.tsx | index | js | a1b2c3d4 | "" (empty string) |
./nested/entry.ts | entry | js | c3d4e5f6 | "nested" |
- JavaScript
- CLI
file system
naming
field, it is used only for bundles that correspond to entrypoints. The names of chunks and copied assets are not affected. Using the JavaScript API, separate template strings can be specified for each type of generated file.
- JavaScript
- CLI
root
The root directory of the project.- JavaScript
- CLI
file system
pages
directory:
- JavaScript
- CLI
file system
pages
directory is the first common ancestor of the entrypoint files, it is considered the project root. This means that the generated bundles live at the top level of the out
directory; there is no out/pages
directory.
This behavior can be overridden by specifying the root
option:
- JavaScript
- CLI
.
as root
, the generated file structure will look like this:
publicPath
A prefix to be appended to any import paths in bundled code. In many cases, generated bundles will contain no import statements. After all, the goal of bundling is to combine all of the code into a single file. However there are a number of cases with the generated bundles will contain import statements.- Asset imports — When importing an unrecognized file type like
*.svg
, the bundler defers to the file loader, which copies the file intooutdir
as is. The import is converted into a variable - External modules — Files and modules can be marked as external, in which case they will not be included in the bundle. Instead, the import statement will be left in the final bundle.
- Chunking. When
splitting
is enabled, the bundler may generate separate “chunk” files that represent code that is shared among multiple entrypoints.
publicPath
will prefix all file paths with the specified value.
- JavaScript
- CLI
define
A map of global identifiers to be replaced at build time. Keys of this object are identifier names, and values are JSON strings that will be inlined.- JavaScript
- CLI
loader
A map of file extensions to built-in loader names. This can be used to quickly customize how certain files are loaded.- JavaScript
- CLI
banner
A banner to be added to the final bundle, this can be a directive like"use client"
for react or a comment block such as a license for the code.
- JavaScript
- CLI
footer
A footer to be added to the final bundle, this can be something like a comment block for a license or just a fun easter egg.- JavaScript
- CLI
drop
Remove function calls from a bundle. For example,--drop=console
will remove all calls to console.log
. Arguments to calls will also be removed, regardless of if those arguments may have side effects. Dropping debugger
will remove all debugger
statements.
- JavaScript
- CLI
Outputs
TheBun.build
function returns a Promise<BuildOutput>
, defined as:
outputs
array contains all the files that were generated by the build. Each artifact implements the Blob interface.
Property | Description |
---|---|
kind | What kind of build output this file is. A build generates bundled entrypoints, code-split “chunks”, sourcemaps, bytecode, and copied assets (like images). |
path | Absolute path to the file on disk |
loader | The loader was used to interpret the file. See Bundler > Loaders to see how Bun maps file extensions to the appropriate built-in loader. |
hash | The hash of the file contents. Always defined for assets. |
sourcemap | The sourcemap file corresponding to this file, if generated. Only defined for entrypoints and chunks. |
BunFile
, BuildArtifact
objects can be passed directly into new Response()
.
BuildArtifact
object to make debugging easier.
Bytecode
Thebytecode: boolean
option can be used to generate bytecode for any JavaScript/TypeScript entrypoints. This can greatly improve startup times for large applications. Only supported for "cjs"
format, only supports "target": "bun"
and dependent on a matching version of Bun. This adds a corresponding .jsc
file for each entrypoint.
- JavaScript
- CLI
Executables
Bun supports “compiling” a JavaScript/TypeScript entrypoint into a standalone executable. This executable contains a copy of the Bun binary.terminal
Logs and errors
On failure,Bun.build
returns a rejected promise with an AggregateError
. This can be logged to the console for pretty printing of the error list, or programmatically read with a try/catch block.
Bun.build
call.
Each item in error.errors
is an instance of BuildMessage
or ResolveMessage
(subclasses of Error
), containing detailed information for each error.
logs
property, which contains bundler warnings and info messages.
Reference
CLI Usage
General Configuration
Set
NODE_ENV=production
and enable minificationUse a bytecode cache when compiling
Intended execution environment for the bundle. One of
browser
, bun
, or
node
Pass custom resolution conditions
Inline environment variables into the bundle as
process.env.$
. To inline
variables matching a prefix, use a glob like FOO_PUBLIC_*
Output & File Handling
Output directory (used when building multiple entry points)
Write output to a specific file
Generate source maps. One of
linked
, inline
, external
, or
none
Add a banner to the output (e.g.
“use client”
for React Server Components)Add a footer to the output (e.g.
// built with bun!
)Module format of the output bundle. One of
esm
, cjs
, or
iife
File Naming
Customize entry point filenames
Customize chunk filenames
Customize asset filenames
Bundling Options
Root directory used when bundling multiple entry points
Enable code splitting for shared modules
Prefix to be added to import paths in bundled code
Exclude modules from the bundle (supports wildcards). Alias:
-e
How to treat dependencies:
external
or bundle
Transpile only — do not bundle
Chunk CSS files together to reduce duplication (only when multiple entry points import CSS)
Minification & Optimization
Re-emit Dead Code Elimination annotations. Disabled when
—minify-whitespace
is usedEnable all minification options
Minify syntax and inline constants
Minify whitespace
Minify variable and function identifiers
Preserve original function and class names when minifying
Development Features
Rebuild automatically when files change
Don’t clear the terminal when rebuilding with
—watch
Enable React Fast Refresh transform (for development testing)
Standalone Executables
Generate a standalone Bun executable containing the bundle. Implies
—production
Prepend arguments to the standalone executable’s
execArgv
Windows Executable Details
Prevent a console window from opening when running a compiled Windows executable
Set an icon for the Windows executable
Set the Windows executable product name
Set the Windows executable company name
Set the Windows executable version (e.g.
1.2.3.4
)Set the Windows executable description
Set the Windows executable copyright notice
Experimental & App Building
(EXPERIMENTAL) Build a web app for production using Bun Bake
(EXPERIMENTAL) Enable React Server Components
When
—app
is set, dump all server files to disk even for static buildsWhen
—app
is set, disable all minification