> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zhcndoc/bun/llms.txt
> Use this file to discover all available pages before exploring further.

# Bundler

> Bun's fast native bundler for JavaScript, TypeScript, JSX, and more

Bun's fast native bundler is available via the `bun build` CLI command or the `Bun.build()` JavaScript API.

### At a glance

* JS API: `await Bun.build({ entrypoints, outdir })`
* CLI: `bun build <entrypoint> --outdir ./out`
* Watch mode: `--watch` for incremental rebuilds
* Targets: `--target browser|bun|node`
* Formats: `--format esm|cjs|iife` (cjs/iife experimental)

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

  <Tab title="CLI">
    ```bash theme={null}
    bun build ./index.tsx --outdir ./build
    ```
  </Tab>
</Tabs>

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

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/zhcndoc-bun/images/bundler-speed.png" alt="Bundling 10 copies of three.js from scratch, with sourcemaps and minification" />
</Frame>

## Why bundle?

Bundlers are a critical piece of infrastructure in the JavaScript ecosystem. Here's a quick overview of why bundling is important:

* **Reduce HTTP requests.** A single package in `node_modules` may consist of hundreds of files, and large applications may have dozens of such dependencies. Loading each of these files with a separate HTTP request becomes untenable very quickly, so bundlers are used to convert our 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 and tools like TypeScript, JSX, and CSS modules that don't run natively in browsers. Bundlers are the natural place to configure this build-time code transformation.
* **Framework features.** Frameworks rely on bundler plugins and code transforms to implement common patterns like file-system routing, client-server code co-location (e.g. `getServerSideProps` or Remix loaders), and server components.
* **Full-stack apps.** Bun's bundler can handle both server-side and client-side code in a single command, with support for optimized production builds and standalone executables. With build-time HTML imports, you can bundle your entire application (frontend assets and backend server) as a single deployable unit.

Let's jump into the bundler's API.

<Note>The Bun bundler is not a replacement for `tsc` for typechecking or generating type declarations.</Note>

## Basic example

Let's build our first bundle. You have the following two files, which implement a simple client-side-rendered React app.

<CodeGroup>
  ```tsx index.tsx theme={null}
  import * as ReactDOM from "react-dom/client";
  import { Component } from "./Component";

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

  ```tsx Component.tsx theme={null}
  export function Component(props: { message: string }) {
    return <h1>{props.message}</h1>;
  }
  ```
</CodeGroup>

Here, `index.tsx` is the "entrypoint" to our application. Commonly, this is a file that performs some side effects like starting a server or—in this case—initializing a React root. Because it uses TypeScript and JSX, we need to bundle our code before it can be sent to the browser.

To create our bundle:

<CodeGroup>
  ```ts build.ts theme={null}
  await Bun.build({
    entrypoints: ["./index.tsx"],
    outdir: "./out",
  });
  ```

  ```bash terminal theme={null}
  bun build ./index.tsx --outdir ./out
  ```
</CodeGroup>

For each file in the `entrypoints` array, Bun will generate a new bundle. This bundle will be written to disk in the `./out` directory (resolved relative to the current working directory). After running the build, the file system looks like this:

```text theme={null}
.
├── index.tsx
├── Component.tsx
└── out
    └── index.js
```

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

```js theme={null}
// out/index.js
// ...
// ~20k lines of code
// including the contents of `react-dom/client` and all its dependencies
// this defines $jsxDEV and $createRoot

// Component.tsx
function Component(props) {
  return $jsxDEV(
    "p",
    {
      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

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

```bash theme={null}
bun build ./index.tsx --outdir ./out --watch
```

## Content types

Like the Bun runtime, the bundler supports an array of file types out of the box. The following table breaks down the bundler's set of default "loaders". Refer to [Bundler > Loaders](/bundler/loaders) for full documentation.

| Extension                                             | Loader                | Description                                                                                                                                                                                                                                                                             |
| ----------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` | JavaScript/TypeScript | Parse and transpile TypeScript/JSX syntax to vanilla JavaScript. Default transformations include dead code elimination and tree shaking. Currently Bun does not attempt to down-convert syntax; the use of recent JavaScript syntax in your code will be reflected in the bundled code. |
| `.json`                                               | JSON                  | Parse JSON files and inline them into the bundle as JavaScript objects.                                                                                                                                                                                                                 |
| `.toml`                                               | TOML                  | Parse TOML files and inline them as JavaScript objects.                                                                                                                                                                                                                                 |
| `.yaml` `.yml`                                        | YAML                  | Parse YAML files and inline them as JavaScript objects.                                                                                                                                                                                                                                 |
| `.txt`                                                | Text                  | Read text files as strings and inline them into the bundle.                                                                                                                                                                                                                             |
| `.html`                                               | HTML                  | Process HTML files, bundling referenced assets (scripts, stylesheets, images, etc.).                                                                                                                                                                                                    |
| `.css`                                                | CSS                   | Bundle all imported CSS files into a single `.css` file that is written to the output directory.                                                                                                                                                                                        |
| `.node` `.wasm`                                       | Native                | These files are supported by the Bun runtime, but during bundling they are treated as assets.                                                                                                                                                                                           |

### Assets

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

<CodeGroup>
  ```ts Input theme={null}
  // bundle entrypoint
  import logo from "./logo.svg";
  console.log(logo);
  ```

  ```ts Output theme={null}
  // bundled output
  var logo = "./logo-a7305bdef.svg";
  console.log(logo);
  ```
</CodeGroup>

The behavior of the file loader is also impacted by [`naming`](#naming) and [`publicPath`](#publicpath).

<Info>Refer to the [Bundler > Loaders](/bundler/loaders) page for complete documentation.</Info>

### Plugins

The behavior described in the table above can be overridden or extended with plugins. Refer to the [Bundler > Loaders](/bundler/loaders) page for complete documentation.

## Key features

### Code splitting

When multiple entry points share code, the bundler can extract shared dependencies into separate chunks. This is called code splitting.

```bash theme={null}
bun build ./entry-a.tsx ./entry-b.tsx --outdir ./out --splitting
```

See [Bundler > API](/bundler/index#splitting) for details.

### Tree shaking

The bundler performs dead code elimination and tree shaking to remove unused code from your bundle. This happens automatically—no configuration required.

### Minification

The bundler supports multiple levels of minification:

```bash theme={null}
bun build ./index.tsx --outdir ./out --minify
bun build ./index.tsx --outdir ./out --minify-whitespace
bun build ./index.tsx --outdir ./out --minify-identifiers
bun build ./index.tsx --outdir ./out --minify-syntax
```

### Source maps

Generate source maps for easier debugging:

```bash theme={null}
bun build ./index.tsx --outdir ./out --sourcemap=external
bun build ./index.tsx --outdir ./out --sourcemap=inline
bun build ./index.tsx --outdir ./out --sourcemap=linked
```

### Environment variables

Inline environment variables at build time:

```bash theme={null}
bun build ./index.tsx --outdir ./out --env inline
bun build ./index.tsx --outdir ./out --env PUBLIC_*
```

## Next steps

<CardGroup cols={2}>
  <Card title="Loaders" icon="file-code" href="/bundler/loaders">
    Learn about file loaders and content types
  </Card>

  <Card title="Plugins" icon="plug" href="/bundler/plugins">
    Extend the bundler with plugins
  </Card>

  <Card title="Macros" icon="wand-magic-sparkles" href="/bundler/macros">
    Run code at build time with macros
  </Card>

  <Card title="Executables" icon="terminal" href="/bundler/executables">
    Compile standalone executables
  </Card>

  <Card title="CSS" icon="paint-brush" href="/bundler/css">
    Bundle and transform CSS
  </Card>

  <Card title="HTML" icon="code" href="/bundler/html">
    Process HTML with bundled assets
  </Card>
</CardGroup>
