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

standalone executables

59 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

bun build --compile flag generates standalone executable

The --compile flag for bun build generates a standalone binary from a TypeScript or JavaScript file. The command bundles all imported files and packages into the executable, along with a copy of the Bun runtime. All built-in Bun and Node.js APIs are supported.

CLI syntax for basic compilation

bun build ./cli.ts --compile --outfile mycli

JavaScript API for basic compilation

await Bun.build({ entrypoints: ["./cli.ts"], compile: { outfile: "./mycli" } });

--target flag for cross-compilation

Use the --target flag to compile a standalone executable for a different operating system, architecture, or version of Bun than the machine running bun build.

Supported compile targets table

The following targets are supported for cross-compilation: | --target | Operating System | Architecture | Modern | Baseline | Libc | |----------|------------------|--------------|--------|----------|------| | bun-linux-x64 | Linux | x64 | ✅ | ✅ | glibc | | bun-linux-arm64 | Linux | arm64 | ✅ | N/A | glibc | | bun-windows-x64 | Windows | x64 | ✅ | ✅ | - | | bun-windows-arm64 | Windows | arm64 | ✅ | N/A | - | | bun-darwin-x64 | macOS | x64 | ✅ | ✅ | - | | bun-darwin-arm64 | macOS | arm64 | ✅ | N/A | - | | bun-linux-x64-musl | Linux | x64 | ✅ | ✅ | musl | | bun-linux-arm64-musl | Linux | arm64 | ✅ | N/A | musl |

Windows x64 baseline and modern variants

bun-windows-x64-baseline targets CPUs from before 2013 (nehalem). bun-windows-x64-modern targets CPUs from 2013 and later (haswell).

Windows exe extension added automatically

When compiling for Windows with --target, if no .exe extension is provided in the outfile, Bun adds it automatically.

SIMD AVX2 CPU requirement and baseline builds

On x64 platforms, Bun uses SIMD optimizations that require a CPU with AVX2 instructions. The -baseline build is for older CPUs without AVX2. If users see "Illegal instruction" errors, they may need to use the baseline version.

Production deployment recommendations for compiled executables

For production deployment, use --compile with --minify and --sourcemap (as linked). This reduces memory usage and improves start time by moving parsing, transpiling, and path resolution costs from runtime to build time.

--compile-exec-argv embeds runtime arguments

The --compile-exec-argv flag embeds runtime arguments that are available at runtime in process.execArgv. Example: bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myapp

JavaScript API for execArgv

await Bun.build({ entrypoints: ["./app.ts"], compile: { execArgv: ["--smol", "--user-agent=MyBot"], outfile: "./myapp" } });

BUN_OPTIONS environment variable passes runtime flags

Standalone executables read the BUN_OPTIONS environment variable, allowing runtime flags to be passed without recompiling. Example: BUN_OPTIONS="--cpu-prof" ./myapp or BUN_OPTIONS="--smol --cpu-prof-md" ./myapp

BUN_BE_BUN environment variable controls executable behavior

Setting the BUN_BE_BUN=1 environment variable causes a standalone executable to run as if it were the bun CLI itself. The executable ignores its bundled entrypoint and exposes the full bun CLI instead. This allows CLI tools built on top of Bun to install packages, bundle dependencies, or run other files without downloading a separate binary.

Config file loading behavior in standalone executables

By default in standalone executables: tsconfig.json and package.json loading is disabled (only needed at development time), while .env and bunfig.toml loading is enabled (often contain runtime configuration that varies per deployment).

--compile-autoload-tsconfig enables runtime tsconfig.json loading

The --compile-autoload-tsconfig flag enables runtime loading of tsconfig.json in compiled executables.

--compile-autoload-package-json enables runtime package.json loading

The --compile-autoload-package-json flag enables runtime loading of package.json in compiled executables.

--no-compile-autoload-dotenv disables .env loading

The --no-compile-autoload-dotenv flag disables .env loading at runtime in compiled executables.

--no-compile-autoload-bunfig disables bunfig.toml loading

The --no-compile-autoload-bunfig flag disables bunfig.toml loading at runtime in compiled executables.

JavaScript API for config autoloading in compile option

The compile option accepts: autoloadTsconfig (boolean, default false), autoloadPackageJson (boolean, default false), autoloadDotenv (boolean, default true), and autoloadBunfig (boolean, default true).

Full-stack executables bundle server and client code

The --compile flag can create a standalone executable that contains both server and client code, suitable for full-stack applications. When importing an HTML file in server code, Bun bundles frontend assets (JavaScript, CSS, etc.) and embeds them into the executable. Bun replaces the HTML import with a manifest object that Bun.serve uses to serve pre-bundled assets.

Worker support in standalone executables

To use workers in a standalone executable, add the worker's entrypoint to the build. Multiple entrypoints must be specified, and Bun bundles each one separately into the executable.

Worker CLI example syntax

bun build --compile ./index.ts ./my-worker.ts --outfile myapp

Worker JavaScript API example

await Bun.build({ entrypoints: ["./index.ts", "./my-worker.ts"], compile: { outfile: "./myapp" } });

SQLite with bun:sqlite import in compiled executables

You can use bun:sqlite imports with bun build --compile. By default, Bun resolves the database relative to the current working directory of the process.

Embed files with type:file import attribute

Use the with { type: "file" } import attribute to embed a file directly into an executable. The import returns a path string pointing to the embedded file, prefixed with /$bunfs/. At build time, Bun reads the file contents, embeds the data into the executable, and replaces the import with an internal path.

Embed file example

import icon from "./icon.png" with { type: "file" }; console.log(icon); // During development: "./icon.png" // After compilation: "/$bunfs/root/icon-a1b2c3d4.png" (internal path)

Reading embedded files with Bun.file()

Bun.file() is the recommended way to read embedded files. It can return file contents as ArrayBuffer, string (for text files), or Blob. Example: const bytes = await file(icon).arrayBuffer(); const text = await file(icon).text(); const blob = file(icon);

Reading embedded files with Node.js fs APIs

Embedded files work with Node.js file system APIs: readFileSync (synchronous), fs.readFile (async), and fs.stat. Example: const iconBuffer = readFileSync(icon); const configData = await fs.readFile(config, "utf-8");

Embed SQLite database with type:sqlite and embed:true

To embed a SQLite database into a compiled executable, set type: "sqlite" and embed: "true" in the import attribute. The database file must already exist on disk. In the compiled executable, the embedded database is read-write and stored in memory, so changes are lost when the executable exits.

Embed SQLite database example

import myEmbeddedDb from "./my.db" with { type: "sqlite", embed: "true" }; console.log(myEmbeddedDb.query("select * from users LIMIT 1").get());

Embed N-API addons into executables

You can embed .node files into executables. If using @mapbox/node-pre-gyp or similar tools, require the .node file directly for proper bundling.

--asset flag embeds files and directories

Use --asset (or compile.assets in the JavaScript API) to embed a file or directory tree into the executable under its original relative path. Embedded files are reachable via import.meta.dir at runtime and via node:fs APIs (existsSync, statSync, readdirSync, readFileSync) and Bun.file().

--asset CLI example

bun build --compile ./index.ts --asset ./public --outfile myapp

Multiple --asset flags for multiple directories

Pass --asset multiple times to embed several directories. Example: --asset ./client --asset ./prerendered for a SvelteKit build. Bun embeds only regular files and skips symlinks and empty subdirectories.

--asset-naming controls embedded file naming

By default, Bun appends a content hash to embedded file names for cache invalidation (e.g., icon-a1b2c3d4.png). Use --asset-naming="[name].[ext]" to keep original names.

--asset-naming CLI example

bun build --compile --asset-naming="[name].[ext]" ./index.ts

--asset-naming JavaScript API example

await Bun.build({ entrypoints: ["./index.ts"], compile: { outfile: "./myapp" }, naming: { asset: "[name].[ext]" } });

Bun.isStandaloneExecutable checks if running from compiled binary

Use Bun.isStandaloneExecutable to check whether the current process is running from a compiled executable. Unlike Bun.embeddedFiles.length > 0, this does not allocate Blob objects and is safe to call at startup.

Bun.embeddedFiles lists all embedded files

Bun.embeddedFiles exposes all embedded files as Blob objects with a name property. Each blob has the embedded file's name (including content hash) and size. Bun.embeddedFiles excludes bundled source code (.ts, .js, etc.) to help protect application source.

Bun.embeddedFiles example usage

for (const blob of embeddedFiles) { console.log(`${blob.name} - ${blob.size} bytes`); } // Output: // icon-a1b2c3d4.png - 4096 bytes // data-e5f6g7h8.json - 256 bytes // template-i9j0k1l2.html - 1024 bytes

--windows-icon sets executable icon

The --windows-icon flag sets a custom icon for Windows executables. Requires a path to a .ico file.

--windows-hide-console hides console window

The --windows-hide-console flag disables the background terminal window for Windows GUI applications.

Windows executable metadata in JavaScript API

The compile.windows option accepts: icon (path to .ico file), hideConsole (boolean), title (application title), publisher (publisher name), version (version string), description (description), and copyright (copyright notice).

Windows metadata restrictions when cross-compiling

Except for hideConsole, Windows metadata flags (icon, title, publisher, version, description, copyright) cannot be used when cross-compiling because they depend on Windows APIs.

Code signing on macOS with codesign

To codesign a standalone executable on macOS (fixing Gatekeeper warnings), use: codesign --deep --force -vvvv --sign "XXXXXXXXXX" ./myapp. An entitlements.plist file with JIT permissions is recommended.

macOS codesign with entitlements example

codesign --deep --force -vvvv --sign "XXXXXXXXXX" --entitlements entitlements.plist ./myapp

macOS entitlements.plist with JIT permissions

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.cs.allow-jit</key> <true/> <key>com.apple.security.cs.allow-unsigned-executable-memory</key> <true/> <key>com.apple.security.cs.disable-executable-page-protection</key> <true/> <key>com.apple.security.cs.allow-dyld-environment-variables</key> <true/> <key>com.apple.security.cs.disable-library-validation</key> <true/> </dict> </plist>

Code splitting support in standalone executables

Standalone executables support code splitting. Use --compile with --splitting to create an executable that loads code-split chunks at runtime.

Code splitting CLI example

bun build --compile --splitting ./src/entry.ts --outfile ./build/entry

Code splitting JavaScript API example

await Bun.build({ entrypoints: ["./src/entry.ts"], compile: true, splitting: true, outdir: "./build" });

Unsupported flags with --compile

The --compile flag does not support: --outdir (use outfile instead), --public-path, --target=node, --target=browser (without HTML entrypoints), or --no-bundle (Bun always bundles everything into the executable).

CompileBuildOptions interface definition

interface CompileBuildOptions { target?: Bun.Build.CompileTarget; outfile?: string; assets?: string[]; execArgv?: string[]; executablePath?: string; autoloadTsconfig?: boolean; autoloadPackageJson?: boolean; autoloadDotenv?: boolean; autoloadBunfig?: boolean; windows?: { icon?: string; hideConsole?: boolean; title?: string; publisher?: string; version?: string; description?: string; copyright?: string; }; }

compile option creates standalone executable

The compile option creates a standalone executable from a JavaScript/TypeScript entrypoint. The executable contains a copy of the Bun binary. Usage: bun build ./cli.tsx --outfile mycli --compile

What gets inlined in standalone HTML output

In standalone HTML builds, the following assets are inlined as data: URIs or embedded tags: <script src="./app.tsx"> becomes <script type="module">...bundled code...</script>; <link rel="stylesheet" href="./styles.css"> becomes <style>...bundled CSS...</style>; <img src="./logo.png"> becomes <img src="data:image/png;base64,...">; <img src="./icon.svg"> becomes <img src="data:image/svg+xml;base64,...">; <video src="./demo.mp4"> becomes <video src="data:video/mp4;base64,...">; <audio src="./click.wav"> becomes <audio src="data:audio/x-wav;base64,...">; <source src="./clip.webm"> becomes <source src="data:video/webm;base64,...">; <video poster="./thumb.jpg"> becomes <video poster="data:image/jpeg;base64,...">; <link rel="icon" href="./favicon.ico"> becomes <link rel="icon" href="data:image/x-icon;base64,...">; <link rel="manifest" href="./app.webmanifest"> becomes <link rel="manifest" href="data:application/manifest+json;base64,...">; CSS url("./bg.png") becomes CSS url(data:image/png;base64,...); CSS @import "./reset.css" is flattened into the <style> tag; CSS url("./font.woff2") becomes CSS url(data:font/woff2;base64,...); JS import "./styles.css" is merged into the <style> tag. Only relative paths are inlined; external URLs and absolute URLs are left untouched.

How standalone HTML bundling works

When using --compile --target=browser with an HTML entrypoint, Bun: (1) parses the HTML and discovers all <script>, <link>, <img>, <video>, <audio>, <source>, and other asset references; (2) bundles all JavaScript/TypeScript/JSX into a single module; (3) bundles all CSS including @import chains and CSS imported from JS into a single stylesheet; (4) converts every relative asset reference into a base64 data: URI; (5) inlines the bundled JS as <script type="module"> before </body>; (6) inlines the bundled CSS as <style> in <head>; (7) outputs a single .html file with no external dependencies.

Multiple HTML files in standalone build

You can pass multiple HTML files as entrypoints to bun build with --compile --target=browser. Each HTML file produces its own standalone .html file in the output directory. Example: bun build --compile --target=browser ./index.html ./about.html --outdir=dist.

Standalone HTML limitations

Standalone HTML builds have three limitations: (1) code splitting is not supported — --splitting cannot be used with --compile --target=browser; (2) large assets increase file size since they are base64-encoded, adding 33% overhead compared to raw binary; (3) external URLs such as CDN links or absolute URLs stay as-is; Bun inlines only relative paths.

Standalone HTML works without server or node_modules

The output of standalone HTML builds is a single plain .html file with no external dependencies. It can be opened by double-clicking from a desktop, embedded in a webview, inserted in an iframe, served from any HTTP server or CDN, uploaded to S3 or any static file host, or shared as a single file like a PDF. No relative paths, no external files, no server required, no node_modules to deploy.

Standalone self-contained HTML output

You can bundle your entire frontend into a single self-contained `.html` file with no external dependencies using `bun build --compile --target=browser ./index.html --outdir=dist`. Bun inlines all JavaScript, CSS, and images directly into the HTML.

Give your agent this brain