Bun.build(): Zig AST Parser & Multi-Threaded Chunk Splitting
- Last updated
- Prerequisites:
- Module bundlers (Webpack, esbuild, Rollup)
- JavaScript AST concepts
- bun
- bundler
- bun-build
- zig
- plugins
- code-splitting
- tree-shaking
Read at your depth
The practical view
`Bun.build()` is Bun's built-in, native JavaScript/TypeScript bundler. You run it from the CLI with `bun build ./src/index.ts --outdir ./dist` or via JavaScript: `await Bun.build({ entrypoints: ['./src/index.ts'], outdir: './dist', minify: true, splitting: true })`. It replaces Webpack, Rollup, and esbuild with zero npm dependencies and natively supports TypeScript, JSX, and custom plugins.
The same idea in other frameworks
Webpack / Rollup / esbuild build configurations.`deno bundle` (deprecated) or esbuild via Deno tasks.`await Bun.build({ entrypoints: ['./src/index.ts'], outdir: './dist' });`.In-browser bundlers like `@esbuild/wasm`.Legacy vs modern
Webpack Config Boilerplate vs Native Bun.build()
Webpack requires multiple JS plugins to handle TS and bundling; `Bun.build` bundles TypeScript natively in milliseconds.
module.exports = { entry: './src/index.ts', module: { rules: [...] } }; // ❌ Slow JS bundlerawait Bun.build({ entrypoints: ['./src/index.ts'], outdir: './dist', minify: true }); // ✅ NEWInterview gotchas
Context
Interviewers test your knowledge of Bun's plugin lifecycle API.
The mechanical answer
Create a plugin object with a `setup(build)` function. Use `build.onLoad({ filter: /\.yaml$/ }, async (args) => { const text = await Bun.file(args.path).text(); return { exports: parseYaml(text), loader: 'object' }; })`. Register the plugin in `Bun.build({ plugins: [myYamlPlugin] })`.
Trap
Plugins in `Bun.build` execute asynchronously, but excessive JavaScript plugin calls can reduce raw Zig bundler throughput.
Context
Checks knowledge of compilation targets in `Bun.build`.
The mechanical answer
Yes. Set `target: 'node'` or `target: 'browser'` or `target: 'bun'`. Setting `target: 'node'` ensures that built-in Node modules (`node:fs`, `node:path`) are treated as external imports rather than bundled into the output.
Trap
The default target is `'browser'`; forgetting to set `target: 'node'` when bundling server tools will cause runtime errors if Node built-ins are bundled unexpectedly.