跳到主要内容

与 esbuild 对比

Bun's bundler API is inspired heavily by esbuild. Migrating to Bun's bundler from esbuild should be relatively painless. This guide will briefly explain why you might consider migrating to Bun's bundler and provide a side-by-side API comparison reference for those who are already familiar with esbuild's API.

There are a few behavioral differences to note.

  • Bundling by default. Unlike esbuild, Bun always bundles by default. This is why the --bundle flag isn't necessary in the Bun example. To transpile each file individually, use Bun.Transpiler.
  • It's just a bundler. Unlike esbuild, Bun's bundler does not include a built-in development server or file watcher. It's just a bundler. The bundler is intended for use in conjunction with Bun.serve and other runtime APIs to achieve the same effect. As such, all options relating to HTTP/file watching are not applicable.

Performance

With a performance-minded API coupled with the extensively optimized Zig-based JS/TS parser, Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark.

CLI API

Bun and esbuild both provide a command-line interface.

$ esbuild <entrypoint> --outdir=out --bundle
$ bun build <entrypoint> --outdir=out

In Bun's CLI, simple boolean flags like --minify do not accept an argument. Other flags like --outdir <path> do accept an argument; these flags can be written as --outdir out or --outdir=out. Some flags like --define can be specified several times: --define foo=bar --define bar=baz.

JavaScript API

Plugin API

Bun's plugin API is designed to be esbuild compatible. Bun doesn't support esbuild's entire plugin API surface, but the core functionality is implemented. Many third-party esbuild plugins will work out of the box with Bun.

备注

Long term, we aim for feature parity with esbuild's API, so if something doesn't work please file an issue to help us prioritize.

Plugins in Bun and esbuild are defined with a builder object.

import type { BunPlugin } from "bun";

const myPlugin: BunPlugin = {
name: "my-plugin",
setup(builder) {
// define plugin
},
};

The builder object provides some methods for hooking into parts of the bundling process. Bun implements onResolve and onLoad; it does not yet implement the esbuild hooks onStart, onEnd, and onDispose, and resolve utilities. initialOptions is partially implemented, being read-only and only having a subset of esbuild's options; use config (same thing but with Bun's BuildConfig format) instead.

import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "my-plugin",
setup(builder) {
builder.onResolve(
{
/* onResolve.options */
},
args => {
return {
/* onResolve.results */
};
},
);
builder.onLoad(
{
/* onLoad.options */
},
args => {
return {
/* onLoad.results */
};
},
);
},
};

onResolve

options

arguments

results

onLoad

options

arguments

results