new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Bundler · all subjects

bun.build/options

104 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

treeShaking option default value

The treeShaking option defaults to true.

write option default behavior

The write option is set to true if outdir or outfile is set, otherwise it defaults to false.

Environment variable inlining example

Given source code: `const apiUrl = process.env.PUBLIC_API_URL; console.log(`API URL: ${apiUrl}`);` and running `PUBLIC_API_URL=https://api.example.com bun build ./index.html --outdir=dist --env=PUBLIC_*`, the bundled output becomes: `const apiUrl = "https://api.example.com"; console.log(`API URL: ${apiUrl}`);`

Environment variable inlining in dev server

To inline environment variables in the dev server, configure the `env` option in bunfig.toml under [serve.static]: `env = "PUBLIC_*"` to only inline vars starting with PUBLIC_ (recommended), `env = "inline"` to inline all vars, or `env = "disable"` to disable inlining (default). Then run: `PUBLIC_API_URL=https://api.example.com bun ./index.html`. This only works with literal `process.env.FOO` references, not `import.meta.env` or indirect access.

HTML bundler support overview

Bun's bundler has first-class support for HTML. You can build static sites, landing pages, and web applications with zero configuration by pointing Bun at your HTML file and it bundles the scripts, stylesheets, and assets the file references.

define option for global identifier replacement

The `define` option is a map of global identifiers to JSON string values that are replaced at build time. Keys are identifier names, values are JSON strings that are inlined into the bundle.

loader option maps file extensions to loaders

The `loader` option is a map of file extensions (e.g., '.png', '.txt') to built-in loader names (e.g., 'dataurl', 'file'). This customizes how specific file types are processed during bundling.

footer option adds code to bundle end

The `footer` option adds a string to the end of the final bundle. Common uses include license headers or comments.

drop option removes function calls

The `drop` option is an array of identifiers and property accesses to remove from the bundle. For example, ['console', 'debugger'] removes all console calls and debugger statements. Arguments to dropped calls are also removed.

features option for compile-time flags

The `features` option is an array of feature flag names for dead code elimination. Features are imported from 'bun:bundle' using `feature('FLAG_NAME')` and are replaced with true/false at bundle time. Unreachable code is eliminated during minification.

optimizeImports skips parsing unused barrel exports

The `optimizeImports` option is an array of package names. For these packages, only imported submodules are parsed instead of parsing the entire barrel file. Works with pure barrel files (all exports are re-exports). Packages with 'sideEffects': false get this automatically.

metafile generates build metadata

The `metafile` option generates metadata about the build. In JavaScript API, accepts boolean (include in result), string (path to write JSON), or object { json: string, markdown: string }. In CLI, use --metafile path or --metafile-md path. Contains input/output file sizes, imports, and exports.

ignoreDCEAnnotations ignores tree-shaking markers

The `ignoreDCEAnnotations` option, when set to true, ignores dead code elimination annotations like @__PURE__ and package.json 'sideEffects' fields. Should only be used as a workaround for incorrect annotations in libraries.

emitDCEAnnotations preserves @__PURE__

The `emitDCEAnnotations` option, when set to true, forces emission of @__PURE__ annotations even when minify.whitespace is true.

throw option controls error handling

The `throw` option (default true) controls whether build failures reject the promise with AggregateError. When false, returns BuildOutput with success: false instead of rejecting.

tsconfig option specifies config file path

The `tsconfig` option specifies a custom tsconfig.json file path for path resolution. Equivalent to --tsconfig-override in CLI.

conditions option for export conditions

The `conditions` option is an array of strings specifying package.json export conditions used when resolving imports. Can also be a single string. Equivalent to --conditions in bun build or bun run. Used for conditional exports per Node.js package exports specification.

BuildOutput return type structure

Bun.build() returns Promise<BuildOutput> with structure: { outputs: BuildArtifact[], success: boolean, logs: Array<BuildMessage | ResolveMessage>, metafile?: BuildMetafile }.

BuildArtifact properties

Each BuildArtifact in outputs has: kind ('entry-point', 'chunk', 'asset', 'sourcemap', 'bytecode'), path (absolute file path), loader (Loader type), hash (content hash, always defined for assets), sourcemap (corresponding sourcemap BuildArtifact or null). BuildArtifact extends Blob.

Loader types supported

Loader types are: 'js', 'jsx', 'ts', 'tsx', 'css', 'json', 'jsonc', 'toml', 'yaml', 'text', 'file', 'napi', 'wasm', 'html'.

target: bun adds @bun pragma

When target: 'bun' is used, all generated bundles are marked with a // @bun pragma, indicating to the Bun runtime that the file doesn't need re-transpilation.

target: bun and format: cjs use @bun-cjs pragma

When using target: 'bun' and format: 'cjs' together, the // @bun @bun-cjs pragma is added and the CommonJS wrapper is not compatible with Node.js.

BuildMessage error class structure

BuildMessage class has: name: string, position?: Position, message: string, level: 'error' | 'warning' | 'info' | 'debug' | 'verbose'.

ResolveMessage error class structure

ResolveMessage extends BuildMessage with additional properties: code: string, referrer: string, specifier: string, importKind: 'entry_point' | 'stmt' | 'require' | 'import' | 'dynamic' | 'require_resolve' | 'at' | 'at_conditional' | 'url' | 'internal'.

MetaFile structure for bundle analysis

BuildMetafile contains: inputs (map of path to {bytes, imports[], format}), outputs (map of path to {bytes, inputs{}, imports[], exports[], entryPoint?, cssBundle?}). Used for bundle analysis, visualization, and dependency tracking.

Shebang detection for bun target

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

packages option: bundle or external

The `packages` option controls whether package dependencies are included in the bundle. Possible values: 'bundle' (default) or 'external'. Bun treats any import not starting with '.', '..', or '/' as a package.

naming option customizes generated file names

The `naming` option customizes output file names using template tokens. As a string: '[dir]/[name].[ext]' (default). As an object: { entry: string, chunk: string, asset: string } for separate templates. Tokens are [name] (entrypoint name), [ext] (extension), [hash] (content hash), [dir] (relative directory path).

root option sets project root directory

The `root` option specifies the project root directory. If unspecified, it is computed as the first common ancestor of all entrypoint files. This affects how the directory structure is preserved in the output.

publicPath prefixes import paths

The `publicPath` option adds a prefix to any import paths in bundled code. Applied to asset imports, external modules, and chunks. For example, 'https://cdn.example.com/' would convert './logo.svg' to 'https://cdn.example.com/logo.svg'.

minify option granular control

The `minify` option can be a boolean or an object. When true, enables all minification. When an object, can specify { whitespace: boolean, identifiers: boolean, syntax: boolean } for granular control. Default is false.

external option marks imports as external

The `external` option is an array of import paths to treat as external. External imports are not included in the bundle; the import statement is left as-is for runtime resolution. Use '*' to mark all imports as external.

banner option adds code to bundle start

The `banner` option adds a string to the beginning of the final bundle. Common uses include directives like '"use client";' for React or license headers.

Bun.build() basic API signature

The `Bun.build()` JavaScript API takes an options object with entrypoints and outdir at minimum: `await Bun.build({ entrypoints: ['./index.tsx'], outdir: './build' })`. It returns a Promise that resolves to a BuildOutput object containing outputs, success, and logs properties.

entrypoints option is required

The `entrypoints` option in Bun.build() is required and must be an array of file paths. Bun generates one bundle per entrypoint.

files option for virtual bundling

The `files` option in Bun.build() accepts a map of file paths to their contents (as string, Blob, TypedArray, or ArrayBuffer). This enables bundling code entirely from memory without files on disk. In-memory files take priority over files on disk, allowing override of specific files.

outdir determines output location

The `outdir` option specifies the directory where output files are written. If not provided in the JavaScript API, bundled code is not written to disk but returned as BuildArtifact objects in result.outputs.

target option values: browser, bun, node

The `target` option specifies the intended execution environment. Values are: 'browser' (default, prioritizes 'browser' export condition), 'bun' (for Bun runtime, adds // @bun pragma), or 'node' (prioritizes 'node' export condition). Default is 'browser'.

format option: esm, cjs, iife

The `format` option specifies the output module format. 'esm' is the default and supports top-level await and import.meta. 'cjs' (experimental) outputs CommonJS and changes default target to 'node'. 'iife' (experimental) is not yet fully documented. Defaults to 'esm'.

splitting option enables code splitting

When `splitting` is set to true, the bundler enables code splitting. Shared code imported by multiple entrypoints is extracted into separate chunk files. Default is false.

env option controls environment variable injection

The `env` option controls how environment variables are handled during bundling. Values are: 'inline' (injects env vars as string literals), 'disable' (disables injection), or a prefix pattern like 'PUBLIC_*' (injects only matching vars).

sourcemap option values

The `sourcemap` option controls sourcemap generation with values: 'none' (default, no sourcemap), 'linked' (separate .js.map file with sourceMappingURL comment), 'external' (separate .js.map file without comment, includes debugId), 'inline' (base64-encoded sourcemap appended to bundle).

Standalone HTML environment variables

Use --env flag to inline environment variables into the bundled JavaScript: `API_URL=https://api.example.com bun build --compile --target=browser --env=inline ./index.html --outdir=dist`. Bun replaces references to process.env.API_URL in JavaScript with the literal value at build time.

Standalone HTML minification

Add --minify flag to minify the JavaScript and CSS in standalone HTML: `bun build --compile --target=browser --minify ./index.html --outdir=dist`. Or use the JavaScript API with `minify: true` option.

Minification mode: String length constant folding

String length constant folding is enabled with --minify-syntax. It evaluates .length property on string literals at compile time. Examples: "hello world".length becomes 11, "test".length becomes 4.

Minification mode: Constructor call simplification

Constructor call simplification is enabled with --minify-syntax. It simplifies constructor calls for built-in types. Examples: new Object() becomes {}, new Array() becomes [], new Array(x, y) becomes [x,y].

Minification mode: Single property object inlining

Single property object inlining is enabled with --minify-syntax. It inlines property access for objects with a single property. Example: ({fn: () => console.log('hi')}).fn becomes () => console.log('hi').

Minification mode: String charCodeAt constant folding

String charCodeAt constant folding is always active. It evaluates charCodeAt() on string literals for ASCII characters. Examples: "hello".charCodeAt(1) becomes 101, "A".charCodeAt(0) becomes 65.

Minification mode: Void 0 equality to null equality

Void 0 equality to null equality is enabled with --minify-syntax. It converts loose equality checks with void 0 to null since they're equivalent. Examples: x == void 0 becomes x == null, x != void 0 becomes x != null.

Minification mode: Negation operator optimization

Negation operator optimization is enabled with --minify-syntax. It moves negation operator through comma expressions. Examples: -(a, b) becomes a,-b, -(x, y, z) becomes x,y,-z.

Minification mode: Import.meta property inlining

Import.meta property inlining is active in bundle mode. It inlines import.meta properties at build time when values are known. Examples: import.meta.dir becomes "/path/to/directory", import.meta.file becomes "filename.js", import.meta.url becomes "file:///full/path/to/file.js".

Minification mode: Variable declaration merging

Variable declaration merging is enabled with --minify-syntax. It merges adjacent variable declarations of the same type. Examples: let a = 1; let b = 2; becomes let a=1,b=2;, const c = 3; const d = 4; becomes const c=3,d=4;.

Minification mode: Expression statement merging

Expression statement merging is enabled with --minify-syntax. It merges adjacent expression statements using comma operator. Example: console.log(1); console.log(2); console.log(3); becomes console.log(1),console.log(2),console.log(3);.

Minification mode: Return statement merging

Return statement merging is enabled with --minify-syntax. It merges expressions before return with comma operator. Example: console.log(x); return y; becomes return console.log(x),y;.

Minification mode: Throw statement merging

Throw statement merging is enabled with --minify-syntax. It merges expressions before throw with comma operator. Example: console.log(x); throw new Error(); becomes throw(console.log(x),new Error());.

Minification mode: TypeScript enum cross-module inlining

TypeScript enum cross-module inlining is enabled with --minify-syntax in bundle mode. It inlines enum values across module boundaries. Example: import { Color } from './lib'; const x = Color.Red; becomes const x=0; when Color.Red is 0.

Minification mode: Computed property enum inlining

Computed property enum inlining is enabled with --minify-syntax. It inlines enum values used as computed object properties. Example: enum Keys { FOO = 'foo' } const obj = { [Keys.FOO]: value } becomes const obj={foo:value}.

Minification mode: Arrow function body shortening

Arrow function body shortening is enabled with --minify-syntax. It uses expression body syntax when an arrow function only returns a value. Examples: () => { return x; } becomes () => x, (a) => { return a + 1; } becomes a => a + 1.

Minification mode: Object property shorthand

Object property shorthand is always active. It uses shorthand syntax when property name and value identifier match. Examples: { x: x, y: y } becomes { x, y }, { name: name, age: age } becomes { name, age }.

keepNames option in Bun.build API

In the JavaScript API, use the keepNames property within the minify object to preserve function and class names while minifying identifiers. Example: minify: { identifiers: true, keepNames: true }

Give your agent this brain