# Bundler (/bundler)

<!-- agent-signals: reading_time_min: 51 · est_tokens: 23103 · updated: 2026-09-23 -->
Related: [Guides](/guides.md), [Bun Runtime](/runtime.md), [Test runner](/test.md)

Use Bun's native bundler through the `bun build` CLI command or the `Bun.build()` JavaScript API.

### At a Glance [#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)

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './build',
    });
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./build
    ```
  </Tab>
</Tabs>

It's fast. The following numbers are from esbuild's [three.js benchmark](https://github.com/oven-sh/bun/tree/main/bench/bundle).

<Frame>
  <img src="/_assets/84398ca6726bf0ab207bb26822c7489fd4b1a82a4addae21e506adbf4339c6b0" caption="Bundling 10 copies of three.js from scratch, with sourcemaps and minification" />
</Frame>

## Why bundle? [#why-bundle]

Bundlers solve several problems:

* **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, so bundlers convert your 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 these must be converted into plain JavaScript and CSS before a browser can consume them. 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.

<Note>
  The Bun bundler is not intended to replace 

  `tsc`

   for typechecking or generating type declarations.
</Note>

## Basic example [#basic-example]

Build your first bundle. You have the following two files, which implement a client-side rendered React app.

<CodeGroup>
  <CodeBlockTabs defaultValue="index.tsx" groupId="component-tsx+index-tsx">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="index.tsx">
        index.tsx
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Component.tsx">
        Component.tsx
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="index.tsx">
      ```tsx icon="/icons/typescript.svg"  
      import * as ReactDOM from "react-dom/client";
      import { Component } from "./Component";

      const root = ReactDOM.createRoot(document.getElementById("root")!);
      root.render(<Component message="Sup!" />);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Component.tsx">
      ```tsx icon="/icons/typescript.svg"  
      export function Component(props: { message: string }) {
        return <h1>{props.message}</h1>;
      }
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

Here, `index.tsx` is the "entrypoint" to the application: the file the bundler starts from. Commonly, this is a script that performs some side effect, like starting a server or, in this case, initializing a React root. Because these files use TypeScript and JSX, the code must be bundled before it can be sent to the browser.

To create the bundle:

<CodeGroup>
  <CodeBlockTabs defaultValue="build.ts" groupId="build-ts+terminal">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="build.ts">
        build.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="terminal">
        terminal
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="build.ts">
      ```ts icon="/icons/typescript.svg"  
      await Bun.build({
        entrypoints: ["./index.tsx"],
        outdir: "./out",
      });
      ```
    </CodeBlockTab>

    <CodeBlockTab value="terminal">
      ```bash icon="terminal"  terminal 
      bun build ./index.tsx --outdir ./out
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

For each file specified in `entrypoints`, Bun generates a new bundle and writes it to the `./out` directory (as resolved from the current working directory). After running the build, the file system looks like this:

```text title="file system" icon="folder-tree"
.
├── index.tsx
├── Component.tsx
└── out
    └── index.js
```

The contents of `out/index.js` look something like this:

```js title="out/index.js" icon="/icons/javascript.svg"
// out/index.js
// ...
// ~20k lines of code
// including the contents of `react-dom/client` and all its dependencies
// this is where the $jsxDEV and $createRoot functions are defined

// Component.tsx
function Component(props) {
  return $jsxDEV(
    "h1",
    {
      children: props.message,
    },
    undefined,
    false,
    undefined,
    this,
  );
}

// index.tsx
var rootNode = document.getElementById("root");
var root = $createRoot(rootNode);
root.render(
  $jsxDEV(
    Component,
    {
      message: "Sup!",
    },
    undefined,
    false,
    undefined,
    this,
  ),
);
```

## Watch mode [#watch-mode]

Like the runtime and test runner, the bundler supports watch mode natively.

```bash icon="terminal" title="terminal" terminal
bun build ./index.tsx --outdir ./out --watch
```

## Content types [#content-types]

Like the Bun runtime, the bundler supports a range of file types by default. The following table lists the bundler's standard "loaders". See [loaders](/bundler/loaders).

| 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. Bun does not down-convert syntax; if you use recent ECMAScript syntax, it appears as-is in the bundled code. |
| `.json`                                               | JSON files are parsed and inlined into the bundle as a JavaScript object.<br /><br />`js<br/>import pkg from "./package.json";<br/>pkg.name; // => "my-package"<br/>`                                                                                                                                                       |
| `.jsonc`                                              | JSON with comments. Files are parsed and inlined into the bundle as a JavaScript object.<br /><br />`js<br/>import config from "./config.jsonc";<br/>config.name; // => "my-config"<br/>`                                                                                                                                   |
| `.toml`                                               | TOML files are parsed and inlined into the bundle as a JavaScript object.<br /><br />`js<br/>import config from "./bunfig.toml";<br/>config.logLevel; // => "debug"<br/>`                                                                                                                                                   |
| `.yaml` `.yml`                                        | YAML files are parsed and inlined into the bundle as a JavaScript object.<br /><br />`js<br/>import config from "./config.yaml";<br/>config.name; // => "my-app"<br/>`                                                                                                                                                      |
| `.txt`                                                | The contents of the text file are read and inlined into the bundle as a string.<br /><br />`js<br/>import contents from "./file.txt";<br/>console.log(contents); // => "Hello, world!"<br/>`                                                                                                                                |
| `.html`                                               | HTML files are processed and any referenced assets (scripts, stylesheets, images) are bundled.                                                                                                                                                                                                                              |
| `.css`                                                | CSS files are bundled together into a single `.css` file in the output directory.                                                                                                                                                                                                                                           |
| `.node` `.wasm`                                       | The Bun runtime supports these files, but the bundler treats them as assets.                                                                                                                                                                                                                                                |

### Assets [#assets]

If the bundler encounters an import with an unrecognized extension, it treats the imported file as an external file. The bundler copies the referenced file as-is into `outdir` and resolves the import as a path to the file.

<CodeGroup>
  <CodeBlockTabs defaultValue="Input" groupId="input+output">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Input">
        Input
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Output">
        Output
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="Input">
      ```ts icon="/icons/typescript.svg"  
      // bundle entrypoint
      import logo from "./logo.svg";
      console.log(logo);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Output">
      ```ts icon="/icons/javascript.svg"  
      // bundled output
      var logo = "./logo-a7305bdef.svg";
      console.log(logo);
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

The exact behavior of the file loader also depends on [`naming`](#naming) and [`publicPath`](#publicpath).

<Info>
  See 

  [loaders](/bundler/loaders)

   for more on the file loader.
</Info>

### Plugins [#plugins]

Plugins can override or extend the behavior described in this table. See [loaders](/bundler/loaders).

## API [#api]

### entrypoints [#entrypoints]

<Badge>
  Required
</Badge>

An array of paths corresponding to the entrypoints of your application. Bun generates one bundle per entrypoint.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    const result = await Bun.build({
      entrypoints: ["./index.ts"],
    });
    // => { success: boolean, outputs: BuildArtifact[], logs: BuildMessage[] }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.ts
    ```
  </Tab>
</Tabs>

### files [#files]

A map of file paths to their contents for in-memory bundling: bundle virtual files that don't exist on disk, or override the contents of files that do. This option is only available in the JavaScript API.

You can provide file contents as a `string`, `Blob`, `TypedArray`, or `ArrayBuffer`.

#### Bundle entirely from memory [#bundle-entirely-from-memory]

You can bundle code without any files on disk by providing all sources in `files`:

```ts title="build.ts" icon="/icons/typescript.svg"
const result = await Bun.build({
  entrypoints: ["/app/index.ts"],
  files: {
    "/app/index.ts": `
      import { greet } from "./greet.ts";
      console.log(greet("World"));
    `,
    "/app/greet.ts": `
      export function greet(name: string) {
        return "Hello, " + name + "!";
      }
    `,
  },
});

const output = await result.outputs[0].text();
console.log(output);
```

When all entrypoints are in the `files` map, Bun uses the current working directory as the root.

#### Override files on disk [#override-files-on-disk]

In-memory files take priority over files on disk, so you can override specific files while keeping the rest of your codebase unchanged:

```ts title="build.ts" icon="/icons/typescript.svg"
// Assume ./src/config.ts exists on disk with development settings
await Bun.build({
  entrypoints: ["./src/index.ts"],
  files: {
    // Override config.ts with production values
    "./src/config.ts": `
      export const API_URL = "https://api.production.com";
      export const DEBUG = false;
    `,
  },
  outdir: "./dist",
});
```

#### Mix disk and virtual files [#mix-disk-and-virtual-files]

Real files on disk can import virtual files, and virtual files can import real files:

```ts title="build.ts" icon="/icons/typescript.svg"
// ./src/index.ts exists on disk and imports "./generated.ts"
await Bun.build({
  entrypoints: ["./src/index.ts"],
  files: {
    // Provide a virtual file that index.ts imports
    "./src/generated.ts": `
      export const BUILD_ID = "${crypto.randomUUID()}";
      export const BUILD_TIME = ${Date.now()};
    `,
  },
  outdir: "./dist",
});
```

Use this for code generation, injecting build-time constants, or testing with mock modules.

### outdir [#outdir]

The directory where output files are written.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    const result = await Bun.build({
      entrypoints: ['./index.ts'],
      outdir: './out'
    });
    // => { success: boolean, outputs: BuildArtifact[], logs: BuildMessage[] }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.ts --outdir ./out
    ```
  </Tab>
</Tabs>

If you don't pass `outdir` to the JavaScript API, Bun does not write bundled code to disk. It returns the bundled files in an array of `BuildArtifact` objects. These objects are Blobs with extra properties; see [Outputs](#outputs).

```ts title="build.ts" icon="/icons/typescript.svg"
const result = await Bun.build({
  entrypoints: ["./index.ts"],
});

for (const res of result.outputs) {
  // Can be consumed as blobs
  await res.text();

  // Bun sets Content-Type and Etag headers
  new Response(res);

  // Can be written manually, but you should use `outdir` in this case.
  Bun.write(path.join("out", res.path), res);
}
```

When `outdir` is set, the `path` property on a `BuildArtifact` is the absolute path it was written to.

### target [#target]

The intended execution environment for the bundle.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.ts'],
      outdir: './out',
      target: 'browser', // default
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.ts --outdir ./out --target browser
    ```
  </Tab>
</Tabs>

Depending on the target, Bun applies different module resolution rules and optimizations.

<Card title="browser" icon="<svg xmlns=&#x22;http://www.w3.org/2000/svg&#x22; viewBox=&#x22;0 0 24 24&#x22; fill=&#x22;none&#x22;><path d=&#x22;M12.5 19L12.5 22&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M10.5 22H14.5&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><circle cx=&#x22;7&#x22; cy=&#x22;7&#x22; r=&#x22;7&#x22; transform=&#x22;matrix(-1 0 0 1 20.5 2)&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M8.5 4C9.15431 4.0385 9.49236 4.35899 10.0735 4.97301C11.1231 6.08206 12.1727 6.1746 12.8724 5.80492C13.922 5.2504 13.04 4.35221 14.2719 3.86409C15.0748 3.54595 15.1868 2.68026 14.7399 2&#x22; stroke=&#x22;currentColor&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M20 10C18.5 10 18.2338 11.2468 17 11C14.5 10.5 13.7916 11.0589 13.7916 12.2511C13.7916 13.4432 13.7916 13.4432 13.2717 14.3373C12.9335 14.9189 12.8153 15.5004 13.4894 16&#x22; stroke=&#x22;currentColor&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M6.5 2C4.64864 3.79995 3.5 6.3082 3.5 9.08251C3.5 14.5598 7.97715 19 13.5 19C16.2255 19 18.6962 17.9187 20.5 16.165&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/></svg>">
  **Default.** For bundles that run in a browser. Prioritizes the `"browser"` export condition when resolving imports.
  Importing built-in modules like `node:events` or `node:path` works, but calling some functions, like `fs.readFile`,
  does not.
</Card>

<Card title="bun" icon="<svg xmlns=&#x22;http://www.w3.org/2000/svg&#x22; viewBox=&#x22;0 0 24 24&#x22; fill=&#x22;none&#x22;><path d=&#x22;M19 4H5C4.06812 4 3.60218 4 3.23463 4.15224C2.74458 4.35523 2.35523 4.74458 2.15224 5.23463C2 5.60218 2 6.06812 2 7C2 7.93188 2 8.39782 2.15224 8.76537C2.35523 9.25542 2.74458 9.64477 3.23463 9.84776C3.60218 10 4.06812 10 5 10H19C19.9319 10 20.3978 10 20.7654 9.84776C21.2554 9.64477 21.6448 9.25542 21.8478 8.76537C22 8.39782 22 7.93188 22 7C22 6.06812 22 5.60218 21.8478 5.23463C21.6448 4.74458 21.2554 4.35523 20.7654 4.15224C20.3978 4 19.9319 4 19 4Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M19 14H5C4.06812 14 3.60218 14 3.23463 14.1522C2.74458 14.3552 2.35523 14.7446 2.15224 15.2346C2 15.6022 2 16.0681 2 17C2 17.9319 2 18.3978 2.15224 18.7654C2.35523 19.2554 2.74458 19.6448 3.23463 19.8478C3.60218 20 4.06812 20 5 20H19C19.9319 20 20.3978 20 20.7654 19.8478C21.2554 19.6448 21.6448 19.2554 21.8478 18.7654C22 18.3978 22 17.9319 22 17C22 16.0681 22 15.6022 21.8478 15.2346C21.6448 14.7446 21.2554 14.3552 20.7654 14.1522C20.3978 14 19.9319 14 19 14Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M6.125 7H6M6.25 7C6.25 7.13807 6.13807 7.25 6 7.25C5.86193 7.25 5.75 7.13807 5.75 7C5.75 6.86193 5.86193 6.75 6 6.75C6.13807 6.75 6.25 6.86193 6.25 7Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M10.125 7H10M10.25 7C10.25 7.13807 10.1381 7.25 10 7.25C9.86193 7.25 9.75 7.13807 9.75 7C9.75 6.86193 9.86193 6.75 10 6.75C10.1381 6.75 10.25 6.86193 10.25 7Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M6.125 17H6M6.25 17C6.25 17.1381 6.13807 17.25 6 17.25C5.86193 17.25 5.75 17.1381 5.75 17C5.75 16.8619 5.86193 16.75 6 16.75C6.13807 16.75 6.25 16.8619 6.25 17Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M10.125 17H10M10.25 17C10.25 17.1381 10.1381 17.25 10 17.25C9.86193 17.25 9.75 17.1381 9.75 17C9.75 16.8619 9.86193 16.75 10 16.75C10.1381 16.75 10.25 16.8619 10.25 17Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/></svg>">
  For bundles that run in 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. Use this target for full-stack applications with build-time HTML imports, where server and client code are bundled together.

  All bundles generated with `target: "bun"` are marked with a `// @bun` pragma, which tells the Bun runtime that there's no need to re-transpile the file before execution.

  If any entrypoint contains a Bun shebang (`#!/usr/bin/env bun`), the bundler defaults to `target: "bun"` instead of `"browser"`.

  When you use `target: "bun"` and `format: "cjs"` together, the bundler adds the `// @bun @bun-cjs` pragma, and the CommonJS wrapper function is not compatible with Node.js.
</Card>

<Card title="node" icon="<svg xmlns=&#x22;http://www.w3.org/2000/svg&#x22; viewBox=&#x22;0 0 24 24&#x22; fill=&#x22;none&#x22;><path d=&#x22;M8 7L16 7&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M8 11L12 11&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/><path d=&#x22;M13 21.5V21C13 18.1716 13 16.7574 13.8787 15.8787C14.7574 15 16.1716 15 19 15H19.5M20 13.3431V10C20 6.22876 20 4.34315 18.8284 3.17157C17.6569 2 15.7712 2 12 2C8.22877 2 6.34315 2 5.17157 3.17157C4 4.34314 4 6.22876 4 10L4 14.5442C4 17.7892 4 19.4117 4.88607 20.5107C5.06508 20.7327 5.26731 20.9349 5.48933 21.1139C6.58831 22 8.21082 22 11.4558 22C12.1614 22 12.5141 22 12.8372 21.886C12.9044 21.8623 12.9702 21.835 13.0345 21.8043C13.3436 21.6564 13.593 21.407 14.0919 20.9081L18.8284 16.1716C19.4065 15.5935 19.6955 15.3045 19.8478 14.9369C20 14.5694 20 14.1606 20 13.3431Z&#x22; stroke=&#x22;currentColor&#x22; stroke-linecap=&#x22;round&#x22; stroke-linejoin=&#x22;round&#x22; stroke-width=&#x22;1.5&#x22;/></svg>">
  For bundles that run in Node.js. Prioritizes the `"node"` export condition when resolving imports. Bun does not
  polyfill the `Bun` global or the built-in `bun:*` modules.
</Card>

### format [#format]

Specifies the module format of the generated bundles.

Bun defaults to `"esm"`, and provides experimental support for `"cjs"` and `"iife"`.

#### format: "esm" - ES Module [#format-esm---es-module]

The default format. Supports ES Module syntax, including top-level await and `import.meta`.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      format: "esm",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --format esm
    ```
  </Tab>
</Tabs>

To use ES Module syntax in browsers, set `format` to `"esm"` and load the bundle with a `<script type="module">` tag.

#### format: "cjs" - CommonJS [#format-cjs---commonjs]

To build a CommonJS module, set `format` to `"cjs"`. When you choose `"cjs"`, the default target changes from `"browser"` (esm) to `"node"` (cjs). CommonJS modules transpiled with `format: "cjs"`, `target: "node"` run in both Bun and Node.js (assuming both support the APIs in use).

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      format: "cjs",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --format cjs
    ```
  </Tab>
</Tabs>

#### format: "iife" - IIFE [#format-iife---iife]

To build an IIFE bundle, set `format` to `"iife"`. Bun wraps the bundle in an immediately invoked function expression and does not support exposing its exports under a global name.

### `jsx` [#jsx]

Configures how JSX is compiled.

**Classic runtime example** (uses `factory` and `fragment`):

<CodeGroup>
  <CodeBlockTabs defaultValue="index.ts" groupId="index-ts+terminal">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="index.ts">
        index.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="terminal">
        terminal
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="index.ts">
      ```ts icon="/icons/typescript.svg"  
      await Bun.build({
        entrypoints: ["./app.tsx"],
        outdir: "./out",
        jsx: {
          factory: "h",
          fragment: "Fragment",
          runtime: "classic",
        },
      });
      ```
    </CodeBlockTab>

    <CodeBlockTab value="terminal">
      ```bash icon="terminal"  terminal 
      # JSX configuration is handled via bunfig.toml or tsconfig.json
      bun build ./app.tsx --outdir ./out
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

**Automatic runtime example** (uses `importSource`):

<CodeGroup>
  <CodeBlockTabs defaultValue="index.ts" groupId="index-ts+terminal">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="index.ts">
        index.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="terminal">
        terminal
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="index.ts">
      ```ts icon="/icons/typescript.svg"  
      await Bun.build({
        entrypoints: ["./app.tsx"],
        outdir: "./out",
        jsx: {
          importSource: "preact",
          runtime: "automatic",
        },
      });
      ```
    </CodeBlockTab>

    <CodeBlockTab value="terminal">
      ```bash icon="terminal"  terminal 
      # JSX configuration is handled via bunfig.toml or tsconfig.json
      bun build ./app.tsx --outdir ./out
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### splitting [#splitting]

Whether to enable code splitting.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      splitting: false, // default
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --splitting
    ```
  </Tab>
</Tabs>

When `true`, the bundler enables code splitting. When multiple entrypoints import the same file or module, the bundler can split that shared code into a separate bundle, known as a **chunk**. Consider the following files:

<CodeGroup>
  <CodeBlockTabs defaultValue="entry-a.ts" groupId="entry-a-ts+entry-b-ts+shared-ts">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="entry-a.ts">
        entry-a.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="entry-b.ts">
        entry-b.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="shared.ts">
        shared.ts
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="entry-a.ts">
      ```ts icon="/icons/typescript.svg"  
      import { shared } from "./shared.ts";
      console.log(shared);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="entry-b.ts">
      ```ts icon="/icons/typescript.svg"  
      import { shared } from "./shared.ts";
      console.log(shared);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="shared.ts">
      ```ts icon="/icons/typescript.svg"  
      export const shared = "shared";
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

To bundle `entry-a.ts` and `entry-b.ts` with code-splitting enabled:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./entry-a.ts', './entry-b.ts'],
      outdir: './out',
      splitting: true,
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./entry-a.ts ./entry-b.ts --outdir ./out --splitting
    ```
  </Tab>
</Tabs>

Running this build with the JavaScript API results in the following files:

```text title="file system" icon="folder-tree"
.
├── entry-a.ts
├── entry-b.ts
├── shared.ts
└── out
    ├── entry-a.js
    ├── entry-b.js
    └── chunk-dqmx6gc8.js
```

The generated `chunk-dqmx6gc8.js` file contains the shared code. To avoid collisions, the file name includes a content hash by default. The `bun build` CLI names this chunk `entry-a-t268ez5g.js` instead of `chunk-<hash>.js`. Customize this with [`naming`](#naming).

Each `import()` of a bundled JavaScript module also becomes its own chunk. Tree shaking applies to these chunks too: if every `import()` of a module lives in code that tree shaking removes — for example inside a function that is only called behind a [`define`](#define) or [`features`](#features) gate that evaluates to `false` — and nothing else in the live output imports the module, its chunk is not written and the module is absent from the [metafile](#metafile)'s `inputs` and `outputs`. Setting `treeShaking: false` keeps every `import()` chunk. This differs from esbuild, which emits a chunk for every reachable `import()` target.

With `target: "bun"`, a `require()` of a bundled ES module becomes a chunk of its own as well. The call is emitted as `import.meta.require("./chunk-<hash>.js")` and stays synchronous — Bun evaluates the chunk when the call runs — so a `require()` inside a function that never runs keeps its module out of the startup working set entirely. Tree shaking treats these chunks like `import()` chunks. `require()` of a CommonJS module is unaffected and keeps returning `module.exports`. A `require()` cycle between such chunks follows Bun's runtime `require()` of an ES module: a module required again while its chunk is still being loaded sees the partially initialized CommonJS placeholder (`{}`) rather than the live bindings the in-chunk wrapper provides. For other targets — and with `splitRequire: false` (`--no-split-require`) — the required module is inlined into the calling chunk behind a lazy wrapper instead, because the call must return synchronously.

#### Tree-shaking `import()` and `require()` results [#tree-shaking-import-and-require-results]

When the result of a string-literal `import()` or `require()` of an ES module is only ever used to read specific exports, the exports nobody reads are dropped from that module — and whatever only they depended on tree-shakes with them. This applies with and without `splitting`; the module is still loaded lazily, exactly where the call is written.

```ts title="entry.ts" icon="/icons/typescript.svg"
const { render } = await import("./markdown"); // keeps `render`
import("./telemetry").then(t => t.init()); // keeps `init`
const { parse } = require("./yaml"); // keeps `parse` (ES module targets only)
await import("./polyfill"); // keeps only side effects
```

Recognized uses: destructuring (`const { a, b: c, ...rest } = await import(x)`, also `let`/`var` and `export const { a } = …`), property access on the awaited value or on a local holding it (`(await import(x)).a`, `const ns = await import(x); ns.a; const { b } = ns`), `.then(({ a }) => …)` / `.then(ns => ns.a)` with an arrow function, per-element destructuring of `await Promise.all([import(x), import(y)])`, the same shapes for `require()`, and a bare `import(x);` / `await import(x);` / `require(x);` statement (nothing observed).

The module keeps every export as soon as one use can't be followed: the namespace is passed, returned, stored, spread or iterated (`() => import(x)`, `fn(ns)`, `{ ...ns }`, `Object.keys(ns)`), accessed with a computed key (or `?.` directly on the `await import(x)` expression), handed to a non-arrow `.then` callback, reached via `import * as ns` elsewhere, or read under a direct `eval`. CommonJS targets always keep everything. The imported module itself is always evaluated; only with `"sideEffects": false` can a module it merely re-exports from be skipped when none of those re-exports are observed.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ["./index.tsx"],
      outdir: "./out",
      target: "bun",
      splitting: true,
      splitRequire: false, // keep require()'d modules in the calling chunk
    });
    ```
  </Tab>

  <Tab title="CLI">
    ```bash title="Terminal" icon="terminal"
    bun build ./index.tsx --outdir ./out --target bun --splitting --no-split-require
    ```
  </Tab>
</Tabs>

### minChunkSize [#minchunksize]

With `splitting`, also fold small side-effect-free chunks into a chunk that more entrypoints load.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      splitting: true,
      minChunkSize: 16 * 1024, // default 0 (off)
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --splitting --min-chunk-size=16384
    ```
  </Tab>
</Tabs>

Code splitting gives each distinct set of importers its own chunk, then folds chunks that are always loaded together: a module that `index.tsx` imports and that a lazily `import()`ed module also imports lives in `index.js`, and the lazy chunk imports it from there, because the lazy module can only load after `index.tsx` has run. That fold never makes an entrypoint load more code, so it is always on.

`minChunkSize` goes further for chunks whose source files add up to fewer than this many bytes and whose modules run nothing at the top level: only declarations, `"sideEffects": false` in their `package.json`, a lazily initialized CommonJS/ESM wrapper, or an import of a CommonJS module (such as `react`) that is already initialized wherever the chunk's code ends up. Such a chunk folds into a chunk loaded by a superset of its importers. Everything it imports must already be loaded whenever that target is, or be side-effect free as well. The extra entrypoints then carry some unused definitions, capped at about 1.5% of what each entrypoint loaded to begin with. No side effect runs earlier than before and nothing lazy becomes eager. Because these rules bound what an entrypoint can end up loading, a large `minChunkSize` is reasonable.

For `target: "browser"`, where every chunk is a request, 16 KiB is a good starting point.

A chunk that absorbs other chunks exports the symbols those chunks' importers need. An entrypoint that has exports of its own never absorbs one, so its module namespace stays as written; an entrypoint without exports can. With `--compile`, nothing folds into the entrypoint's own chunk.

### modulePreload [#modulepreload]

With `splitting` and `target: "browser"`, the browser would otherwise discover a chunk's own imports only after downloading and parsing it, one level per round trip. Bun writes a `<link rel="modulepreload">` into HTML entrypoints for every chunk the page's script statically imports, and every `import()` first inserts one for each chunk its target statically imports (transitively), so the whole dependency chain downloads in parallel. Outside a document (workers, server-side) the `import()` helper does nothing. Inserted links copy the nonce from a `<meta property="csp-nonce" nonce="...">` tag if the page has one. Enabled by default; set `modulePreload: false` (`--no-module-preload`) to emit plain `import()` calls and no links.

### plugins [#plugins-1]

A list of plugins to use during bundling.

```ts title="build.ts" icon="/icons/typescript.svg"
await Bun.build({
  entrypoints: ["./index.tsx"],
  outdir: "./out",
  plugins: [
    /* ... */
  ],
});
```

The runtime and the bundler share Bun's plugin system. See [plugins](/bundler/plugins).

### env [#env]

Controls how environment variables are handled during bundling. Internally, this option uses `define` to inject environment variables into the bundle; `env` is a shorthand for specifying which ones.

#### env: "inline" [#env-inline]

Injects environment variables into the bundled output by converting `process.env.FOO` references to string literals containing the actual environment variable values.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      env: "inline",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --env inline
    ```
  </Tab>
</Tabs>

For the input below:

```js title="input.js" icon="/icons/javascript.svg"
// input.js
console.log(process.env.FOO);
console.log(process.env.BAZ);
```

The generated bundle contains the following code:

```js title="output.js" icon="/icons/javascript.svg"
// output.js
console.log("bar");
console.log("123");
```

#### env: "PUBLIC\_\*" (prefix) [#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. Use a prefix to inline public values, like public-facing URLs or client-side tokens, without injecting private credentials into output bundles.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      
      // Inline all env vars that start with "ACME_PUBLIC_"
      env: "ACME_PUBLIC_*",
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --env ACME_PUBLIC_*
    ```
  </Tab>
</Tabs>

For example, given the following environment variables:

```bash icon="terminal" title="terminal" terminal
FOO=bar BAZ=123 ACME_PUBLIC_URL=https://acme.com
```

And source code:

```tsx icon="/icons/typescript.svg" title="index.tsx"
console.log(process.env.FOO);
console.log(process.env.ACME_PUBLIC_URL);
console.log(process.env.BAZ);
```

The generated bundle contains the following code:

```js title="output.js" icon="/icons/javascript.svg"
console.log(process.env.FOO);
console.log("https://acme.com");
console.log(process.env.BAZ);
```

#### env: "disable" [#env-disable]

Disables environment variable injection entirely.

### sourcemap [#sourcemap]

Specifies the type of sourcemap to generate.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      sourcemap: 'linked', // default 'none'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --sourcemap=linked
    ```
  </Tab>
</Tabs>

| 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. You can customize the base URL in this comment with `--public-path`.<br /><br />`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.<br /><br />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.<br /><br />`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.<br /><br />`js<br/>// <bundled code here><br/><br/>//# sourceMappingURL=data:application/json;base64,<encoded sourcemap here><br/>`                                                                                                                                                                   |

The associated `*.js.map` sourcemap is a JSON file containing an equivalent `debugId` property.

### minify [#minify]

Whether to enable minification. Default `false`.

To enable all minification options:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      minify: true, // default false
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --minify
    ```
  </Tab>
</Tabs>

To granularly enable certain minifications:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      minify: {
        whitespace: true,
        identifiers: true,
        syntax: true,
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --minify-whitespace --minify-identifiers --minify-syntax
    ```
  </Tab>
</Tabs>

### external [#external]

A list of import paths to consider external. Defaults to `[]`.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ["lodash", "react"], // default: []
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --external lodash --external react
    ```
  </Tab>
</Tabs>

An external import is not included in the final bundle. Instead, the bundler leaves the import statement as-is, to be resolved at runtime.

For instance, consider the following entrypoint file:

```tsx icon="/icons/typescript.svg" title="index.tsx"
import _ from "lodash";
import { z } from "zod";

const value = z.string().parse("Hello world!");
console.log(_.upperCase(value));
```

Normally, bundling `index.tsx` would generate a bundle containing the entire source code of the "zod" package. To leave the import statement as-is instead, mark it as external:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ['zod'],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --external zod
    ```
  </Tab>
</Tabs>

The generated bundle looks something like this:

```js title="out/index.js" icon="/icons/javascript.svg"
import { z } from "zod";

// ...
// the contents of the "lodash" package
// including the `_.upperCase` function

var value = z.string().parse("Hello world!");
console.log(_.upperCase(value));
```

To mark all imports as external, use the wildcard `*`:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      external: ['*'],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --external '*'
    ```
  </Tab>
</Tabs>

### packages [#packages]

Controls whether package dependencies are included in the bundle. Possible values: `bundle` (default), `external`. Bun treats any import whose path does not start with `.`, `..`, or `/` as a package.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.ts'],
      packages: 'external',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.ts --packages external
    ```
  </Tab>
</Tabs>

### naming [#naming]

Customizes the generated file names. Defaults to `[dir]/[name].[ext]`.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: "[dir]/[name].[ext]", // default
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --entry-naming "[dir]/[name].[ext]"
    ```
  </Tab>
</Tabs>

By default, the names of the generated bundles are based on the name of the associated entrypoint.

```text title="file system" icon="folder-tree"
.
├── index.tsx
└── out
    └── index.js
```

With multiple entrypoints, the generated file hierarchy reflects the directory structure of the entrypoints.

```text title="file system" icon="folder-tree"
.
├── index.tsx
└── nested
    └── index.tsx
└── out
    ├── index.js
    └── nested
        └── index.js
```

The `naming` field customizes the names and locations of the generated files. It accepts a template string. Bun uses the template for all bundles that correspond to entrypoints and replaces the following tokens with their 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: 8 lowercase alphanumeric characters. If two outputs with different contents would print the same characters, both get enough extra characters to differ (as do the outputs that reference them). `[hash9]` through `[hash13]` set a wider minimum; `[hash13]` is the full 64-bit hash.
* `[dir]` - The relative path from the project root to the parent directory of the source file.

For example:

| Token               | `[name]` | `[ext]` | `[hash]`   | `[dir]`             |
| ------------------- | -------- | ------- | ---------- | ------------------- |
| `./index.tsx`       | `index`  | `js`    | `a1b2c3d4` | `""` (empty string) |
| `./nested/entry.ts` | `entry`  | `js`    | `c3d4e5f6` | `"nested"`          |

Combine these tokens to create a template string. For instance, to include the hash in the generated bundle names:

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: 'files/[dir]/[name]-[hash].[ext]',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --entry-naming 'files/[dir]/[name]-[hash].[ext]'
    ```
  </Tab>
</Tabs>

This build would result in the following file structure:

```text title="file system" icon="folder-tree"
.
├── index.tsx
└── out
    └── files
        └── index-a1b2c3d4.js
```

When you provide a string for the `naming` field, Bun uses it only for bundles that correspond to entrypoints. The names of chunks and copied assets are not affected. In the JavaScript API, you can specify a separate template string for each type of generated file.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      naming: {
        // default values
        entry: '[dir]/[name].[ext]',
        chunk: '[name]-[hash].[ext]',
        asset: '[name]-[hash].[ext]',
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out \
      --entry-naming '[dir]/[name].[ext]' \
      --chunk-naming '[name]-[hash].[ext]' \
      --asset-naming '[name]-[hash].[ext]'
    ```
  </Tab>
</Tabs>

### root [#root]

The root directory of the project.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./pages/a.tsx', './pages/b.tsx'],
      outdir: './out',
      root: '.',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./pages/a.tsx ./pages/b.tsx --outdir ./out --root .
    ```
  </Tab>
</Tabs>

If unspecified, Bun uses the first common ancestor of all entrypoint files as the root. Consider the following file structure:

```text title="file system" icon="folder-tree"
.
└── pages
  └── index.tsx
  └── settings.tsx
```

Build both entrypoints in the `pages` directory:

<Tabs>
  <Tab title="JavaScript">
    ```js
    await Bun.build({
      entrypoints: ['./pages/index.tsx', './pages/settings.tsx'],
      outdir: './out',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash
    bun build ./pages/index.tsx ./pages/settings.tsx --outdir ./out
    ```
  </Tab>
</Tabs>

This would result in a file structure like this:

```text title="file system" icon="folder-tree"
.
└── pages
  └── index.tsx
  └── settings.tsx
└── out
  └── index.js
  └── settings.js
```

The `pages` directory is the first common ancestor of the entrypoint files, so Bun treats it as the project root. As a result, the generated bundles live at the top level of the `out` directory; there is no `out/pages` directory.

Override this by specifying the `root` option:

<Tabs>
  <Tab title="JavaScript">
    ```js
    await Bun.build({
      entrypoints: ['./pages/index.tsx', './pages/settings.tsx'],
      outdir: './out',
      root: '.',
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash
    bun build ./pages/index.tsx ./pages/settings.tsx --outdir ./out --root .
    ```
  </Tab>
</Tabs>

With `.` as `root`, the generated file structure looks like this:

```
.
└── pages
  └── index.tsx
  └── settings.tsx
└── out
  └── pages
    └── index.js
    └── settings.js
```

### publicPath [#publicpath]

A prefix added to any import paths in bundled code.

In many cases, generated bundles contain no import statements; the goal of bundling is to combine all of the code into a single file. In a few cases, though, the generated bundles contain import statements:

* **Asset imports** — When importing an unrecognized file type like `*.svg`, the bundler defers to the file loader, which copies the file into `outdir` as is. The import is converted into a variable.
* **External modules** — Files and modules marked as external are not included in the bundle. Instead, the bundler leaves the import statement 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.

In any of these cases, the final bundles may contain paths to other files. By default these imports are relative. Here is an example of an asset import:

<CodeGroup>
  <CodeBlockTabs defaultValue="Input" groupId="input+output">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Input">
        Input
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Output">
        Output
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="Input">
      ```ts icon="/icons/typescript.svg"  
      import logo from "./logo.svg";
      console.log(logo);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Output">
      ```ts icon="/icons/javascript.svg"  
      var logo = "./logo-a7305bdef.svg";
      console.log(logo);
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

Setting `publicPath` prefixes all file paths with the specified value.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      publicPath: 'https://cdn.example.com/', // default is undefined
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --public-path 'https://cdn.example.com/'
    ```
  </Tab>
</Tabs>

The output file would now look something like this.

```js title="out/index.js" icon="/icons/javascript.svg"
var logo = "https://cdn.example.com/logo-a7305bdef.svg";
```

### define [#define]

A map of global identifiers to be replaced at build time. Keys of this object are identifiers or dotted property paths such as `process.env.NODE_ENV`, and values are JSON strings, identifiers, or property paths that are inlined.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      define: {
        STRING: JSON.stringify("value"),
        "nested.boolean": "true",
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --define STRING='"value"' --define nested.boolean=true
    ```
  </Tab>
</Tabs>

### loader [#loader]

A map of file extensions to built-in loader names. Use this to customize how certain files are loaded.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      loader: {
        ".png": "dataurl",
        ".txt": "file",
      },
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --loader .png:dataurl --loader .txt:file
    ```
  </Tab>
</Tabs>

### banner [#banner]

A banner added to the final bundle. This can be a directive like `"use client"` for React, or a comment block such as a license.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      banner: '"use client";'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --banner '"use client";'
    ```
  </Tab>
</Tabs>

### footer [#footer]

A footer added to the final bundle. This can be a comment block for a license or a fun easter egg.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      footer: '// built with love in SF'
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --footer '// built with love in SF'
    ```
  </Tab>
</Tabs>

### drop [#drop]

Removes function calls from a bundle. For example, `--drop=console` removes all calls to `console.log`. Bun also removes the arguments to dropped calls, even if they have side effects. Dropping `debugger` removes all `debugger` statements.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      drop: ["console", "debugger", "anyIdentifier.or.propertyAccess"],
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --drop console --drop debugger
    ```
  </Tab>
</Tabs>

### features [#features]

Enable compile-time feature flags for dead code elimination: conditionally include or exclude code paths at bundle time using `import { feature } from "bun:bundle"`.

```ts title="app.ts" icon="/icons/typescript.svg"
import { feature } from "bun:bundle";

if (feature("PREMIUM")) {
  // Only included when PREMIUM flag is enabled
  initPremiumFeatures();
}

if (feature("DEBUG")) {
  // Only included when DEBUG flag is enabled
  console.log("Debug mode");
}
```

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./app.ts'],
      outdir: './out',
      features: ["PREMIUM"],  // PREMIUM=true, DEBUG=false
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./app.ts --outdir ./out --feature PREMIUM
    ```
  </Tab>
</Tabs>

Bun replaces the `feature()` function with `true` or `false` at bundle time. When minification is also enabled, Bun eliminates the unreachable code:

```ts title="Input" icon="/icons/typescript.svg"
import { feature } from "bun:bundle";
const mode = feature("PREMIUM") ? "premium" : "free";
```

```js title="Output (with --feature PREMIUM --minify)" icon="/icons/javascript.svg"
var mode = "premium";
```

```js title="Output (without --feature PREMIUM, with --minify)" icon="/icons/javascript.svg"
var mode = "free";
```

**Key behaviors:**

* `feature()` requires a string literal argument — dynamic values are not supported
* Bun completely removes the `bun:bundle` import from the output
* Works with `bun build`, `bun run`, and `bun test`
* You can enable multiple flags: `--feature FLAG_A --feature FLAG_B`
* For type safety, augment the `Registry` interface to restrict `feature()` to known flags

**Use cases:**

* Platform-specific code (`feature("SERVER")` vs `feature("CLIENT")`)
* Environment-based features (`feature("DEVELOPMENT")`)
* Gradual feature rollouts
* A/B testing variants
* Paid tier features

**Type safety:** By default, `feature()` accepts any string. To get autocomplete and catch typos at compile time, create an `env.d.ts` file (or add to an existing `.d.ts`) and augment the `Registry` interface:

```ts title="env.d.ts" icon="/icons/typescript.svg"
declare module "bun:bundle" {
  interface Registry {
    features: "DEBUG" | "PREMIUM" | "BETA_FEATURES";
  }
}
```

Ensure the file is included in your `tsconfig.json` (for example, `"include": ["src", "env.d.ts"]`). Now `feature()` only accepts those flags, and invalid strings like `feature("TYPO")` become type errors.

### optimizeImports [#optimizeimports]

Skip parsing unused submodules of barrel files (re-export index files). When you import only a few named exports from a large library, normally the bundler parses every file the barrel re-exports. With `optimizeImports`, the bundler parses only the submodules you use.

```ts title="build.ts" icon="/icons/typescript.svg"
await Bun.build({
  entrypoints: ["./app.ts"],
  outdir: "./out",
  optimizeImports: ["antd", "@mui/material", "lodash-es"],
});
```

For example, `import { Button } from 'antd'` normally parses all \~3000 modules that `antd/index.js` re-exports. With `optimizeImports: ['antd']`, the bundler parses only the `Button` submodule.

This works for **pure barrel files** — files where every named export is a re-export (`export { X } from './x'`). If a barrel file has any local exports (`export const foo = ...`), or if any importer uses `import *`, the bundler loads all submodules.

The bundler always loads `export *` re-exports (it never defers them) to avoid circular resolution issues. It defers only named re-exports (`export { X } from './x'`) that no importer uses.

**Automatic mode:** Packages with `"sideEffects": false` in their `package.json` get barrel optimization automatically — no `optimizeImports` config needed. Use `optimizeImports` for packages that don't have this field.

**Plugins:** Resolve and load plugins work with barrel optimization. Deferred submodules go through the plugin pipeline when they are eventually loaded.

### Re-exported namespaces [#re-exported-namespaces]

Property reads on an import that turns out to be a module namespace are linked straight to the export they name, the same as a named import. This covers namespaces reached indirectly:

Each of these shapes of `lib.ts` qualifies:

```ts icon="/icons/typescript.svg"
// import { z } from "./lib";  z.object()
import * as z from "./external";
export { z };
```

```ts icon="/icons/typescript.svg"
// import z from "./lib";  z.object()
import * as z from "./external";
export default z;
```

```ts icon="/icons/typescript.svg"
// import { ns } from "./lib";  ns.object()
export * as ns from "./external";
```

```ts icon="/icons/typescript.svg"
// import lib from "./lib";  lib.object()
export function object() {}
export * as default from "./lib";
```

In each case the member access compiles to a direct reference to `object`, the `exports` object for `./external` is not created unless something else uses the namespace as a value (`Object.keys(z)`, `{ ...z }`, passing `z` around), and the exports you don't touch are tree-shaken. One level is resolved (`ns.a.b` binds `a`). Calling a function this way passes `undefined` as `this`, as with `import * as ns; ns.fn()`.

Assignments (`z.x = 1`), optional chains, and non-literal computed keys (`z[key]`) are left as property accesses; `z["object"]` is treated like `z.object`. `export default someImport` is followed only when it ends at a namespace; a default that snapshots a `let` export keeps snapshot semantics.

The same applies to the default import of a CommonJS module whose `exports.x = ...` assignments the bundler lifted to ES module exports, such as `react` and `scheduler`. The default import of a CommonJS module is its `module.exports`, which is that module's namespace, so `import React from "react"; React.useState()` compiles to a direct call of the lifted `useState` binding. This holds while every use of `React` reads, calls or assigns one of its properties: `React.useState`, `React[key]`, `const { useState } = React`. A write, `React.useLayoutEffect = React.useEffect`, goes through a namespace object whose setters assign the lifted binding, so every importer sees the new value, the same as a write to `module.exports`. Code that holds `React` itself as a value (`fn(React)`, `Object.keys(React)`, `const R = React`, a re-export) or deletes one of its properties can change the object in ways a namespace object cannot pass on to the lifted bindings (`Object.defineProperty`, `delete`, `Object.freeze`). The module then keeps its CommonJS wrapper and the default import is the real `module.exports` object. This rule looks at `import React from` only. `ns.default` on `import * as ns`, the `default` of an `import()` and the `this` of a call like `React.fn()` are still the namespace object of a module that stays lifted. `React.default`, and `ns.default` on `import * as ns`, is the lifted `default` export when the module has one, and otherwise the namespace itself, as `module.exports` is in Node. A module that sets both `exports.__esModule` and `exports.default` keeps its CommonJS wrapper when the importer is not an ES module by type (`.mjs`, `.mts`, or `"type": "module"`), because the default import then depends on that flag at run time. An `import()` of a module that does not set both resolves to that same namespace object as `default`, with or without code splitting.

### deprecatedNamespaceObjectSetters [#deprecatednamespaceobjectsetters]

Default `true`. When a namespace object does have to be created, each property currently gets a getter and a setter; the setter accepts `ns.foo = value` without throwing (reads still return the module's binding). Set this to `false` to emit getter-only namespace objects, which is what a future Bun release will do unconditionally. The namespace of a lifted CommonJS module is not affected: it stands in for `module.exports`, so its setters assign the lifted bindings either way.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    await Bun.build({
      entrypoints: ['./index.tsx'],
      outdir: './out',
      deprecatedNamespaceObjectSetters: false,
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./index.tsx --outdir ./out --no-deprecated-namespace-object-setters
    ```
  </Tab>
</Tabs>

### metafile [#metafile]

Generate metadata about the build in a structured format. The metafile describes every input and output file: sizes, imports, and exports. Use it for:

* **Bundle analysis**: Understand what's contributing to bundle size
* **Visualization**: Feed into tools like [esbuild's bundle analyzer](https://esbuild.github.io/analyze/)
* **Dependency tracking**: See the full import graph of your application
* **CI integration**: Track bundle size changes over time

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    const result = await Bun.build({
      entrypoints: ['./src/index.ts'],
      outdir: './dist',
      metafile: true,
    });

    if (result.metafile) {
      // Analyze inputs
      for (const [path, meta] of Object.entries(result.metafile.inputs)) {
        console.log(`${path}: ${meta.bytes} bytes`);
      }

      // Analyze outputs
      for (const [path, meta] of Object.entries(result.metafile.outputs)) {
        console.log(`${path}: ${meta.bytes} bytes`);
      }

      // Save for external analysis tools
      await Bun.write('./dist/meta.json', JSON.stringify(result.metafile));
    }
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    bun build ./src/index.ts --outdir ./dist --metafile=./dist/meta.json
    ```
  </Tab>
</Tabs>

#### Markdown metafile [#markdown-metafile]

Use `--metafile-md` to generate a markdown metafile, which is LLM-friendly and readable in the terminal:

```bash icon="terminal" title="terminal" terminal
bun build ./src/index.ts --outdir ./dist --metafile-md=./dist/meta.md
```

You can use both `--metafile` and `--metafile-md` together:

```bash icon="terminal" title="terminal" terminal
bun build ./src/index.ts --outdir ./dist --metafile=./dist/meta.json --metafile-md=./dist/meta.md
```

#### `metafile` option formats [#metafile-option-formats]

In the JavaScript API, `metafile` accepts several forms:

```ts title="build.ts" icon="/icons/typescript.svg"
// Boolean — include metafile in the result object
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: true,
});

// String — write JSON metafile to a specific path
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: "./dist/meta.json",
});

// Object — specify separate paths for JSON and markdown output
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  metafile: {
    json: "./dist/meta.json",
    markdown: "./dist/meta.md",
  },
});
```

The metafile structure contains:

```ts
interface BuildMetafile {
  inputs: {
    [path: string]: {
      bytes: number;
      imports: Array<{
        path: string;
        kind: ImportKind;
        original?: string; // Original specifier before resolution
        entryPoint?: string; // import() / require() split into another output file: the input that file was built from
        external?: boolean;
      }>;
      format?: "esm" | "cjs" | "json" | "css";
    };
  };
  outputs: {
    [path: string]: {
      bytes: number;
      inputs: {
        [path: string]: { bytesInOutput: number };
      };
      imports: Array<{ path: string; kind: ImportKind }>;
      exports: string[];
      entryPoint?: string;
      cssBundle?: string; // Associated CSS file for JS entry points
    };
  };
}
```

## Outputs [#outputs]

The `Bun.build` function returns a `Promise<BuildOutput>`, defined as:

```ts title="build.ts" icon="/icons/typescript.svg"
interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<object>; // see docs for details
  metafile?: BuildMetafile; // only when metafile: true
}

interface BuildArtifact extends Blob {
  kind: "entry-point" | "chunk" | "asset" | "sourcemap" | "bytecode";
  path: string;
  loader: Loader;
  hash: string | null;
  sourcemap: BuildArtifact | null;
}
```

The `outputs` array contains all the files generated by the build. Each artifact implements the Blob interface.

```ts title="build.ts" icon="/icons/typescript.svg"
const build = await Bun.build({
  /* */
});

for (const output of build.outputs) {
  await output.arrayBuffer(); // => ArrayBuffer
  await output.bytes(); // => Uint8Array
  await output.text(); // string
}
```

Each artifact also contains the following properties:

| 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 used to interpret the file. See [loaders](/bundler/loaders) for how Bun maps file extensions to built-in loaders.                               |
| `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.                                                      |

Similar to `BunFile`, `BuildArtifact` objects can be passed directly into `new Response()`.

```ts title="build.ts" icon="/icons/typescript.svg"
const build = await Bun.build({
  /* */
});

const artifact = build.outputs[0];

// Content-Type header is automatically set
return new Response(artifact);
```

The Bun runtime pretty-prints `BuildArtifact` objects to help with debugging.

<CodeGroup>
  <CodeBlockTabs defaultValue="build.ts" groupId="build-ts+shell-output">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="build.ts">
        build.ts
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Shell output">
        Shell output
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="build.ts">
      ```ts icon="/icons/typescript.svg"  
      // build.ts
      const build = await Bun.build({
        /* */
      });

      const artifact = build.outputs[0];
      console.log(artifact);
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Shell output">
      ```bash  
      bun run build.ts

      BuildArtifact (entry-point) {
        path: "./index.js",
        loader: "tsx",
        kind: "entry-point",
        hash: "824a039620219640",
        Blob (74756 bytes) {
          type: "text/javascript;charset=utf-8"
        },
        sourcemap: BuildArtifact (sourcemap) {
          path: "./index.js.map",
          loader: "file",
          kind: "sourcemap",
          hash: "e7178cda3e72e301",
          Blob (24765 bytes) {
            type: "application/json;charset=utf-8"
          },
          sourcemap: null
        }
      }
      ```
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

## Bytecode [#bytecode]

The `bytecode: boolean` option generates bytecode for any JavaScript/TypeScript entrypoints, which can greatly improve startup times for large applications. Requires `"target": "bun"` and a matching version of Bun.

* **CommonJS**: Works with or without `compile: true`. Generates a `.jsc` file alongside each entrypoint.
* **ESM**: Requires `compile: true`. Bun embeds the bytecode and module metadata in the standalone executable.

Without an explicit `format`, bytecode defaults to CommonJS.

The `bytecodeDepth: number` option (a non-negative integer) limits how many levels of nested functions are compiled ahead of time (`0` = only each module's top-level code). Functions past the limit are compiled from source when first called. Defaults to all.

<Tabs>
  <Tab title="JavaScript">
    ```ts title="build.ts" icon="/icons/typescript.svg"
    // CommonJS bytecode (generates .jsc files)
    await Bun.build({
      entrypoints: ["./index.tsx"],
      outdir: "./out",
      bytecode: true,
    })

    // ESM bytecode (requires compile)
    await Bun.build({
      entrypoints: ["./index.tsx"],
      outfile: "./mycli",
      bytecode: true,
      format: "esm",
      compile: true,
    })
    ```
  </Tab>

  <Tab title="CLI">
    ```bash icon="terminal" title="terminal" terminal
    # CommonJS bytecode
    bun build ./index.tsx --outdir ./out --bytecode

    # ESM bytecode (requires --compile)
    bun build ./index.tsx --outfile ./mycli --bytecode --format=esm --compile
    ```
  </Tab>
</Tabs>

## Executables [#executables]

Bun supports "compiling" a JavaScript/TypeScript entrypoint into a standalone executable. This executable contains a copy of the Bun binary.

```bash icon="terminal" title="terminal" terminal
bun build ./cli.tsx --outfile mycli --compile
./mycli
```

See [standalone executables](/bundler/executables).

## Logs and errors [#logs-and-errors]

On failure, `Bun.build` returns a rejected promise with an `AggregateError`. Log it to the console to pretty-print the error list, or read it programmatically with a try/catch block.

```ts title="build.ts" icon="/icons/typescript.svg"
try {
  const result = await Bun.build({
    entrypoints: ["./index.tsx"],
    outdir: "./out",
  });
} catch (e) {
  // TypeScript does not allow annotations on the catch clause
  const error = e as AggregateError;
  console.error("Build Failed");

  // Example: Using the built-in formatter
  console.error(error);

  // Example: Serializing the failure as a JSON string.
  console.error(JSON.stringify(error, null, 2));
}
```

Most of the time, an explicit try/catch is not needed, as Bun prints uncaught exceptions. You can use a top-level await on the `Bun.build` call instead.

Each item in `error.errors` is an instance of `BuildMessage` or `ResolveMessage` (subclasses of `Error`), containing detailed information for each error.

```ts title="build.ts" icon="/icons/typescript.svg"
class BuildMessage {
  name: string;
  position?: Position;
  message: string;
  level: "error" | "warning" | "info" | "debug" | "verbose";
}

class ResolveMessage extends BuildMessage {
  code: string;
  referrer: string;
  specifier: string;
  importKind: ImportKind;
}
```

On build success, the returned object contains a `logs` property, which contains bundler warnings and info messages.

```ts title="build.ts" icon="/icons/typescript.svg"
const result = await Bun.build({
  entrypoints: ["./index.tsx"],
  outdir: "./out",
});

if (result.logs.length > 0) {
  console.warn("Build succeeded with warnings:");
  for (const message of result.logs) {
    // Bun pretty-prints the message object
    console.warn(message);
  }
}
```

## Reference [#reference]

```ts icon="/icons/typescript.svg" expandable title="Typescript Definitions"
interface Bun {
  build(options: BuildOptions): Promise<BuildOutput>;
}

interface BuildConfig {
  entrypoints: string[]; // list of file path
  outdir?: string; // output directory
  target?: Target; // default: "browser"
  /**
   * Output module format. Top-level await is only supported for `"esm"`.
   *
   * Can be:
   * - `"esm"`
   * - `"cjs"` (**experimental**)
   * - `"iife"` (**experimental**)
   *
   * @default "esm"
   */
  format?: "esm" | "cjs" | "iife";
  /**
   * JSX configuration object for controlling JSX transform behavior
   */
  jsx?: {
    runtime?: "automatic" | "classic";
    importSource?: string;
    factory?: string;
    fragment?: string;
    sideEffects?: boolean;
    development?: boolean;
  };
  naming?:
    | string
    | {
        chunk?: string;
        entry?: string;
        asset?: string;
      };
  root?: string; // project root
  splitting?: boolean; // default false, enable code splitting
  splitRequire?: boolean; // default true, with splitting and target "bun": require() of an ES module is a chunk too
  minChunkSize?: number; // default 0, also fold side-effect-free chunks smaller than this many source bytes
  modulePreload?: boolean; // default true, with splitting and target "browser": <link rel=modulepreload> the chunks an entrypoint or import() depends on
  plugins?: BunPlugin[];
  external?: string[];
  packages?: "bundle" | "external";
  publicPath?: string;
  define?: Record<string, string>;
  loader?: { [k in string]: Loader };
  sourcemap?: "none" | "linked" | "inline" | "external" | boolean; // default: "none", true -> "inline"
  /**
   * package.json `exports` conditions used when resolving imports
   *
   * Equivalent to `--conditions` in `bun build` or `bun run`.
   *
   * https://nodejs.org/api/packages.html#exports
   */
  conditions?: Array<string> | string;

  /**
   * Controls how environment variables are handled during bundling.
   *
   * Can be one of:
   * - `"inline"`: Injects environment variables into the bundled output by converting `process.env.FOO`
   *   references to string literals containing the actual environment variable values
   * - `"disable"`: Disables environment variable injection entirely
   * - A string ending in `*`: Inlines environment variables that match the given prefix.
   *   For example, `"MY_PUBLIC_*"` will only include env vars starting with "MY_PUBLIC_"
   */
  env?: "inline" | "disable" | `${string}*`;
  minify?:
    | boolean
    | {
        whitespace?: boolean;
        syntax?: boolean;
        identifiers?: boolean;
      };
  /**
   * Ignore dead code elimination/tree-shaking annotations such as @__PURE__ and package.json
   * "sideEffects" fields. This should only be used as a temporary workaround for incorrect
   * annotations in libraries.
   */
  ignoreDCEAnnotations?: boolean;
  /**
   * Force emitting @__PURE__ annotations even if minify.whitespace is true.
   */
  emitDCEAnnotations?: boolean;
  /**
   * Emit a setter per property on bundled module namespace objects (default).
   * @deprecated set to `false` for getter-only namespace objects; this becomes
   * the only behavior in a future release.
   */
  deprecatedNamespaceObjectSetters?: boolean;

  /**
   * Generate bytecode for the output. This can dramatically improve cold
   * start times, but will make the final output larger and slightly increase
   * memory usage.
   *
   * - CommonJS: works with or without `compile: true`
   * - ESM: requires `compile: true`
   *
   * Without an explicit `format`, defaults to CommonJS.
   *
   * Must be `target: "bun"`
   * @default false
   */
  bytecode?: boolean;
  /**
   * How many levels of nested functions to compile to bytecode ahead of time
   * (a non-negative integer; `0` = only each module's top-level code).
   * Only used when `bytecode: true`.
   * @default undefined (all nested functions)
   */
  bytecodeDepth?: number;
  /**
   * Build-time optimizations for `bytecode` builds.
   */
  optimize?: {
    /**
     * Run JavaScriptCore's build-time optimization passes over the generated bytecode.
     * @default true
     */
    bytecode?: boolean;
  };
  /**
   * Add a banner to the bundled code such as "use client";
   */
  banner?: string;
  /**
   * Add a footer to the bundled code such as a comment block like
   *
   * `// made with bun!`
   */
  footer?: string;

  /**
   * Drop function calls to matching property accesses.
   */
  drop?: string[];

  /**
   * - When set to `true`, the returned promise rejects with an AggregateError when a build failure happens.
   * - When set to `false`, returns a {@link BuildOutput} with `{success: false}`
   *
   * @default true
   */
  throw?: boolean;

  /**
   * Custom tsconfig.json file path to use for path resolution.
   * Equivalent to `--tsconfig-override` in the CLI.
   */
  tsconfig?: string;

  outdir?: string;
}

interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<BuildMessage | ResolveMessage>;
}

interface BuildArtifact extends Blob {
  path: string;
  loader: Loader;
  hash: string | null;
  kind: "entry-point" | "chunk" | "asset" | "sourcemap" | "bytecode";
  sourcemap: BuildArtifact | null;
}

type Loader =
  | "js"
  | "jsx"
  | "ts"
  | "tsx"
  | "css"
  | "json"
  | "jsonc"
  | "toml"
  | "yaml"
  | "text"
  | "file"
  | "napi"
  | "wasm"
  | "html";

interface BuildOutput {
  outputs: BuildArtifact[];
  success: boolean;
  logs: Array<BuildMessage | ResolveMessage>;
}

declare class ResolveMessage {
  readonly name: "ResolveMessage";
  readonly position: Position | null;
  readonly code: string;
  readonly message: string;
  readonly referrer: string;
  readonly specifier: string;
  readonly importKind:
    | "entry_point"
    | "stmt"
    | "require"
    | "import"
    | "dynamic"
    | "require_resolve"
    | "at"
    | "at_conditional"
    | "url"
    | "internal";
  readonly level: "error" | "warning" | "info" | "debug" | "verbose";

  toString(): string;
}
```

***

## CLI Usage [#cli-usage]

```bash
bun build <entry points>
```

### General Configuration [#general-configuration]

<ParamField path="--production" type="boolean">
  Set <code>NODE\_ENV=production</code> and enable minification
</ParamField>

<ParamField path="--bytecode" type="boolean">
  Use a bytecode cache when compiling
</ParamField>

<ParamField path="--bytecode-depth" type="number">
  How many levels of nested functions to compile to bytecode ahead of time (a non-negative integer). Defaults to all
</ParamField>

<ParamField path="--no-optimize-bytecode" type="boolean">
  With <code>--bytecode</code>: skip the build-time bytecode optimization passes
</ParamField>

<ParamField path="--target" type="string" default="browser">
  Intended execution environment for the bundle. One of <code>browser</code>, <code>bun</code>, or <code>node</code>
</ParamField>

<ParamField path="--conditions" type="string">
  Pass custom resolution conditions
</ParamField>

<ParamField path="--env" type="string" default="disable">
  Inline environment variables into the bundle as <code>process.env.${name}</code>. To inline variables matching a
  prefix, use a glob like <code>FOO\_PUBLIC\_\*</code>
</ParamField>

### Output & File Handling [#output--file-handling]

<ParamField path="--outdir" type="string" default="dist">
  Output directory (used when building multiple entry points)
</ParamField>

<ParamField path="--outfile" type="string">
  Write output to a specific file
</ParamField>

<ParamField path="--metafile" type="string">
  Write a JSON file with metadata about the build
</ParamField>

<ParamField path="--metafile-md" type="string">
  Write a markdown file with a visualization of the module graph (LLM-friendly)
</ParamField>

<ParamField path="--sourcemap" type="string" default="none">
  Generate source maps. One of <code>linked</code>, <code>inline</code>, <code>external</code>, or <code>none</code>
</ParamField>

<ParamField path="--banner" type="string">
  Add a banner to the output (e.g. <code>"use client"</code> for React Server Components)
</ParamField>

<ParamField path="--footer" type="string">
  Add a footer to the output (e.g. <code>// built with bun!</code>)
</ParamField>

<ParamField path="--format" type="string" default="esm">
  Module format of the output bundle. One of <code>esm</code>, <code>cjs</code>, or <code>iife</code>. Defaults to{" "}
  <code>cjs</code> when <code>--bytecode</code> is used.
</ParamField>

### File Naming [#file-naming]

<ParamField path="--entry-naming" type="string" default="[dir]/[name].[ext]">
  Customize entry point filenames
</ParamField>

<ParamField path="--chunk-naming" type="string" default="[name]-[hash].[ext]">
  Customize chunk filenames
</ParamField>

<ParamField path="--asset-naming" type="string" default="[name]-[hash].[ext]">
  Customize asset filenames
</ParamField>

### Bundling Options [#bundling-options]

<ParamField path="--root" type="string">
  Root directory used when bundling multiple entry points
</ParamField>

<ParamField path="--splitting" type="boolean">
  Enable code splitting for shared modules
</ParamField>

<ParamField path="--min-chunk-size" type="number">
  With `--splitting`, also fold side-effect-free chunks smaller than this many source bytes into a chunk loaded by a
  superset of their importers
</ParamField>

<ParamField path="--no-module-preload" type="boolean">
  With `--splitting` and `--target browser`, don't emit `<link rel="modulepreload">` for the chunks an entrypoint or
  `import()` depends on
</ParamField>

<ParamField path="--public-path" type="string">
  Prefix the bundler adds to import paths in bundled code
</ParamField>

<ParamField path="--external" type="string">
  Exclude modules from the bundle (supports wildcards). Alias: <code>-e</code>
</ParamField>

<ParamField path="--allow-unresolved" type="string" default="*">
  Allow unresolved dynamic import()/require() specifiers matching these glob patterns. Pass <code>''</code> to allow
  opaque specifiers
</ParamField>

<ParamField path="--reject-unresolved" type="boolean">
  Fail the build on any dynamic import()/require() specifier that cannot be resolved at build time
</ParamField>

<ParamField path="--packages" type="string" default="bundle">
  How to treat dependencies: <code>external</code> or <code>bundle</code>
</ParamField>

<ParamField path="--no-bundle" type="boolean">
  Transpile only — do not bundle
</ParamField>

<ParamField path="--css-chunking" type="boolean">
  Chunk CSS files together to reduce duplication (only when multiple entry points import CSS)
</ParamField>

### Minification & Optimization [#minification--optimization]

<ParamField path="--emit-dce-annotations" type="boolean" default="true">
  Re-emit Dead Code Elimination annotations. Disabled when <code>--minify-whitespace</code> is used
</ParamField>

<ParamField path="--no-deprecated-namespace-object-setters" type="boolean">
  Emit getter-only module namespace objects (assigning to a property throws, like a real namespace). This becomes the
  default in a future release
</ParamField>

<ParamField path="--minify" type="boolean">
  Enable all minification options
</ParamField>

<ParamField path="--minify-syntax" type="boolean">
  Minify syntax and inline constants
</ParamField>

<ParamField path="--minify-whitespace" type="boolean">
  Minify whitespace
</ParamField>

<ParamField path="--minify-identifiers" type="boolean">
  Minify variable and function identifiers
</ParamField>

<ParamField path="--keep-names" type="boolean">
  Preserve original function and class names when minifying
</ParamField>

### Development Features [#development-features]

<ParamField path="--watch" type="boolean">
  Rebuild automatically when files change
</ParamField>

<ParamField path="--no-clear-screen" type="boolean">
  Don’t clear the terminal when rebuilding with <code>--watch</code>
</ParamField>

<ParamField path="--react-fast-refresh" type="boolean">
  Enable React Fast Refresh transform (for development testing)
</ParamField>

<ParamField path="--react-compiler" type="boolean">
  Run the React Compiler over `.jsx`/`.tsx` files, automatically memoizing components and hooks. The bundler derives the
  output mode from `--target` (`browser` → client, `bun`/`node` → ssr). Experimental.
</ParamField>

### Standalone Executables [#standalone-executables]

<ParamField path="--compile" type="boolean">
  Generate a standalone Bun executable containing the bundle
</ParamField>

<ParamField path="--compile-exec-argv" type="string">
  Prepend arguments to the standalone executable’s <code>execArgv</code>
</ParamField>

<ParamField path="--compile-jit-policy" type="number" default="1">
  JIT tier-up threshold scale the executable starts with; <code>1</code> is the normal JIT policy. See
  <code>Bun.unsafe.setJITPolicy</code>
</ParamField>

<ParamField path="--compile-autoload-dotenv" type="boolean" default="true">
  Enable autoloading of <code>.env</code> files in the standalone executable
</ParamField>

<ParamField path="--no-compile-autoload-dotenv" type="boolean">
  Disable autoloading of <code>.env</code> files in the standalone executable
</ParamField>

<ParamField path="--compile-autoload-bunfig" type="boolean" default="true">
  Enable autoloading of <code>bunfig.toml</code> in the standalone executable
</ParamField>

<ParamField path="--no-compile-autoload-bunfig" type="boolean">
  Disable autoloading of <code>bunfig.toml</code> in the standalone executable
</ParamField>

<ParamField path="--compile-autoload-tsconfig" type="boolean" default="false">
  Enable autoloading of <code>tsconfig.json</code> at runtime in the standalone executable
</ParamField>

<ParamField path="--no-compile-autoload-tsconfig" type="boolean">
  Disable autoloading of <code>tsconfig.json</code> at runtime in the standalone executable
</ParamField>

<ParamField path="--compile-autoload-package-json" type="boolean" default="false">
  Enable autoloading of <code>package.json</code> at runtime in the standalone executable
</ParamField>

<ParamField path="--no-compile-autoload-package-json" type="boolean">
  Disable autoloading of <code>package.json</code> at runtime in the standalone executable
</ParamField>

<ParamField path="--compile-executable-path" type="string">
  Path to a Bun executable to use for cross-compilation instead of downloading
</ParamField>

<ParamField path="--asset" type="string">
  Embed a file or directory into the compiled executable under its basename; a directory keeps its internal tree, so{" "}
  <code>--asset ./static/public</code> embeds <code>public/...</code> (requires <code>--compile</code>)
</ParamField>

### Windows Executable Details [#windows-executable-details]

<ParamField path="--windows-hide-console" type="boolean">
  Prevent a console window from opening when running a compiled Windows executable
</ParamField>

<ParamField path="--windows-icon" type="string">
  Set an icon for the Windows executable
</ParamField>

<ParamField path="--windows-title" type="string">
  Set the Windows executable product name
</ParamField>

<ParamField path="--windows-publisher" type="string">
  Set the Windows executable company name
</ParamField>

<ParamField path="--windows-version" type="string">
  Set the Windows executable version (e.g. <code>1.2.3.4</code>)
</ParamField>

<ParamField path="--windows-description" type="string">
  Set the Windows executable description
</ParamField>

<ParamField path="--windows-copyright" type="string">
  Set the Windows executable copyright notice
</ParamField>

### Experimental & App Building [#experimental--app-building]

<ParamField path="--app" type="boolean">
  <b>(EXPERIMENTAL)</b> Build a web app for production using Bun Bake
</ParamField>

<ParamField path="--server-components" type="boolean">
  <b>(EXPERIMENTAL)</b> Enable React Server Components
</ParamField>

<ParamField path="--debug-dump-server-files" type="boolean">
  When <code>--app</code> is set, dump all server files to disk even for static builds
</ParamField>

<ParamField path="--debug-no-minify" type="boolean">
  When <code>--app</code> is set, disable all minification
</ParamField>
