跳到主要内容

`Bun.build`

Bun's fast native bundler is now in beta. It can be used via the bun build CLI command or the Bun.build() JavaScript API.

It's fast. The numbers below represent performance on esbuild's three.js benchmark.

Why bundle?

The bundler is a key piece of infrastructure in the JavaScript ecosystem. As a brief overview of why bundling is so important:

  • Reducing HTTP requests. A single package in node_modules may consist of hundreds of files, and large applications may have dozens of such dependencies. Loading each of these files with a separate HTTP request becomes untenable very quickly, so bundlers are used to convert our application source code into a smaller number of self-contained "bundles" that can be loaded with a single request.
  • Code transforms. Modern apps are commonly built with languages or tools like TypeScript, JSX, and CSS modules, all of which must be converted into plain JavaScript and CSS before they can be consumed by a browser. The bundler is the natural place to configure these transformations.
  • Framework features. Frameworks rely on bundler plugins & code transformations to implement common patterns like file-system routing, client-server code co-location (think getServerSideProps or Remix loaders), and server components.

Let's jump into the bundler API.

备注

Note that the Bun bundler is not intended to replace tsc for typechecking or generating type declarations.

Basic example

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

import * as ReactDOM from 'react-dom/client';
import {Component} from "./Component"

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

Here, index.tsx is the "entrypoint" to our application. Commonly, this will be a script that performs some side effect, like starting a server or—in this case—initializing a React root. Because we're using TypeScript & JSX, we need to bundle our code before it can be sent to the browser.

To create our bundle:

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

.
├── index.tsx
├── Component.tsx
└── out
└── index.js

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

// ...
// ~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("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));
Tutorial: Run this file in your browser

We can load this file in the browser to see our app in action. Create an index.html file in the out directory:

$ touch out/index.html

Then paste the following contents into it:

<html>
<body>
<div id="root"></div>
<script type="module" src="/index.js"></script>
</body>
</html>

Then spin up a static file server serving the out directory:

$ bunx serve out

Visit http://localhost:5000 to see your bundled app in action.

Watch mode

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

$ 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 standard "loaders". Refer to Bundler > File types for full documentation.

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 resolved as a path to the file.

// bundle entrypoint
import logo from "./logo.svg";
console.log(logo);
备注

The exact behavior of the file loader is also impacted by naming and publicPath.

Refer to the Bundler > Loaders page for more complete documentation on the file loader.

Plugins

The behavior described in this table can be overridden or extended with plugins. Refer to the Bundler > Loaders page for complete documentation.

API

entrypoints

Required. An array of paths corresponding to the entrypoints of our application. One bundle will be generated for each entrypoint.

outdir

The directory where output files will be written.

If outdir is not passed to the JavaScript API, bundled code will not be written to disk. Bundled files are returned in an array of BuildArtifact objects. These objects are Blobs with extra properties; see Outputs for complete documentation.

const result = await Bun.build({
entrypoints: ["./index.ts"],
});

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

// Bun will set 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 will be the absolute path to where it was written to.

target

The intended execution environment for the bundle.

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

format

Specifies the module format to be used in the generated bundles.

Currently the bundler only supports one module format: "esm". Support for "cjs" and "iife" are planned.

await Bun.build({
entrypoints: ['./index.tsx'],
outdir: './out',
format: "esm",
})

splitting

Whether to enable code splitting.

When true, the bundler will enable code splitting. When multiple entrypoints both import the same file, module, or set of files/modules, it's often useful to split the shared code into a separate bundle. This shared bundle is known as a chunk. Consider the following files:

import { shared } from './shared.ts';

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

Running this build will result in the following files:

.
├── entry-a.tsx
├── entry-b.tsx
├── shared.tsx
└── out
├── entry-a.js
├── entry-b.js
└── chunk-2fce6291bf86559d.js

The generated chunk-2fce6291bf86559d.js file contains the shared code. To avoid collisions, the file name automatically includes a content hash by default. This can be customized with naming.

plugins

A list of plugins to use during bundling.

Bun implements a universal plugin system for both Bun's runtime and bundler. Refer to the plugin documentation for complete documentation.

sourcemap

Specifies the type of sourcemap to generate.

备注

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.

// <generated bundle code>

//# debugId=<DEBUG ID>

  • "inline"

  • A sourcemap is generated and appended to the end of the generated bundle as a base64 payload.

    // <bundled code here>

    //# sourceMappingURL=data:application/json;base64,<encoded sourcemap here>

    The associated *.js.map sourcemap will be a JSON file containing an equivalent debugId property.

minify

Whether to enable minification. Default false.

备注

When targeting bun, identifiers will be minified by default.

To enable all minification options:

To granularly enable certain minifications:

external

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

An external import is one that will not be included in the final bundle. Instead, the import statement will be left as-is, to be resolved at runtime.

For instance, consider the following entrypoint file:

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. If instead, we want to leave the import statement as-is, we can mark it as external:

The generated bundle will look something like this:

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 *:

await Bun.build({
entrypoints: ['./index.tsx'],
outdir: './out',
external: ['*'],
})

packages

Control whatever package dependencies are included to bundle or not. Possible values: bundle (default), external. Bun threats any import which path do not start with ., .. or / as package.

naming

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

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

.
├── index.tsx
└── out
└── index.js

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

.
├── index.tsx
└── nested
└── index.tsx
└── out
├── index.js
└── nested
└── index.js

The names and locations of the generated files can be customized with the naming field. This field accepts a template string that is used to generate the filenames for all bundles corresponding to entrypoints. where the following tokens are replaced with their corresponding values:

  • [name] - The name of the entrypoint file, without the extension.
  • [ext] - The extension of the generated bundle.
  • [hash] - A hash of the bundle contents.
  • [dir] - The relative path from the project root to the parent directory of the source file.

For example:

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

This build would result in the following file structure:

.
├── index.tsx
└── out
└── files
└── index-a1b2c3d4.js

When a string is provided for the naming field, it is used only for bundles that correspond to entrypoints. The names of chunks and copied assets are not affected. Using the JavaScript API, separate template strings can be specified for each type of generated file.

root

The root directory of the project.

If unspecified, it is computed to be the first common ancestor of all entrypoint files. Consider the following file structure:

.
└── pages
└── index.tsx
└── settings.tsx

We can build both entrypoints in the pages directory:

This would result in a file structure like this:

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

Since the pages directory is the first common ancestor of the entrypoint files, it is considered the project root. This means that the generated bundles live at the top level of the out directory; there is no out/pages directory.

This behavior can be overridden by specifying the root option:

By specifying . as root, the generated file structure will look like this:

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

publicPath

A prefix to be appended to any import paths in bundled code.

In many cases, generated bundles will contain no import statements. After all, the goal of bundling is to combine all of the code into a single file. However there are a number of cases with the generated bundles will contain import statements.

  • Asset imports — When importing an unrecognized file type like *.svg, the bundler defers to the file loader, which copies the file into outdir as is. The import is converted into a variable
  • External modules — Files and modules can be marked as external, in which case they will not be included in the bundle. Instead, the import statement will be left in the final bundle.
  • Chunking. When splitting is enabled, the bundler may generate separate "chunk" files that represent code that is shared among multiple entrypoints.

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 a simple asset import:

import logo from './logo.svg';
console.log(logo);

Setting publicPath will prefix all file paths with the specified value.

The output file would now look something like this.

- var logo = './logo-a7305bdef.svg';
+ var logo = 'https://cdn.example.com/logo-a7305bdef.svg';

define

A map of global identifiers to be replaced at build time. Keys of this object are identifier names, and values are JSON strings that will be inlined.

备注

This is not needed to inline process.env.NODE_ENV, as Bun does this automatically.

await Bun.build({
entrypoints: ['./index.tsx'],
outdir: './out',
define: {
STRING: JSON.stringify("value"),
"nested.boolean": "true",
},
})

loader

A map of file extensions to built-in loader names. This can be used to quickly customize how certain files are loaded.

await Bun.build({
entrypoints: ['./index.tsx'],
outdir: './out',
loader: {
".png": "dataurl",
".txt": "file",
},
})

Outputs

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

interface BuildOutput {
outputs: BuildArtifact[];
success: boolean;
logs: Array<object>; // see docs for details
}

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

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

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:

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

const build = await Bun.build({
/* */
});

const artifact = build.outputs[0];

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

The Bun runtime implements special pretty-printing of BuildArtifact object to make debugging easier.

// build.ts
const build = await Bun.build({/* */});

const artifact = build.outputs[0];
console.log(artifact);

Executables

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

$ bun build ./cli.tsx --outfile mycli --compile
$ ./mycli

Refer to Bundler > Executables for complete documentation.

Logs and errors

Bun.build only throws if invalid options are provided. Read the success property to determine if the build was successful; the logs property will contain additional details.

const result = await Bun.build({
entrypoints: ["./index.tsx"],
outdir: "./out",
});

if (!result.success) {
console.error("Build failed");
for (const message of result.logs) {
// Bun will pretty print the message object
console.error(message);
}
}

Each message is either a BuildMessage or ResolveMessage object, which can be used to trace what problems happened in the build.

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;
}

If you want to throw an error from a failed build, consider passing the logs to an AggregateError. If uncaught, Bun will pretty-print the contained messages nicely.

if (!result.success) {
throw new AggregateError(result.logs, "Build failed");
}

Reference

interface Bun {
build(options: BuildOptions): Promise<BuildOutput>;
}

interface BuildOptions {
entrypoints: string[]; // required
outdir?: string; // default: no write (in-memory only)
format?: "esm"; // later: "cjs" | "iife"
target?: "browser" | "bun" | "node"; // "browser"
splitting?: boolean; // true
plugins?: BunPlugin[]; // [] // See https://bun.sh/docs/bundler/plugins
loader?: { [k in string]: Loader }; // See https://bun.sh/docs/bundler/loaders
manifest?: boolean; // false
external?: string[]; // []
sourcemap?: "none" | "inline" | "linked" | "external" | boolean; // "none"
root?: string; // computed from entrypoints
naming?:
| string
| {
entry?: string; // '[dir]/[name].[ext]'
chunk?: string; // '[name]-[hash].[ext]'
asset?: string; // '[name]-[hash].[ext]'
};
publicPath?: string; // e.g. http://mydomain.com/
minify?:
| boolean // false
| {
identifiers?: boolean;
whitespace?: boolean;
syntax?: boolean;
};
}

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

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

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

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;
}