diff --git a/docs/README.md b/docs/README.md index 484dea173f6f..dea5f88dc704 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,8 +21,8 @@ Run the development server: mint dev ``` -The site will be available at `http://localhost:3000`. +The site is served at `http://localhost:3000`. ## Contributing -Contributions are welcome! Please open an issue or submit a pull request. +Contributions are welcome. Open an issue or submit a pull request. diff --git a/docs/bundler/bytecode.mdx b/docs/bundler/bytecode.mdx index ac6999fc3175..f2ca8185ee81 100644 --- a/docs/bundler/bytecode.mdx +++ b/docs/bundler/bytecode.mdx @@ -3,19 +3,19 @@ title: Bytecode Caching description: Speed up JavaScript execution with bytecode caching in Bun's bundler --- -Bytecode caching is a build-time optimization that dramatically improves application startup time by pre-compiling your JavaScript to bytecode. For example, when compiling TypeScript's `tsc` with bytecode enabled, startup time improves by **2x**. +Bytecode caching is a build-time optimization that improves startup time by pre-compiling your JavaScript to bytecode. For example, when compiling TypeScript's `tsc` with bytecode enabled, startup time improves by **2x**. ## Usage ### Basic usage (CommonJS) -Enable bytecode caching with the `--bytecode` flag. Without `--format`, this defaults to CommonJS: +Enable bytecode caching with the `--bytecode` flag. Without `--format`, the output format defaults to CommonJS: ```bash terminal icon="terminal" bun build ./index.ts --target=bun --bytecode --outdir=./dist ``` -This generates two files: +The build writes two files: - `dist/index.js` - Your bundled JavaScript (CommonJS) - `dist/index.jsc` - The bytecode cache file @@ -28,7 +28,7 @@ bun ./dist/index.js # Automatically uses index.jsc ### With standalone executables -When creating executables with `--compile`, bytecode is embedded into the binary. Both ESM and CommonJS formats are supported: +When you create an executable with `--compile`, Bun embeds the bytecode in the binary. Both ESM and CommonJS work: ```bash terminal icon="terminal" # ESM (requires --compile) @@ -38,17 +38,17 @@ bun build ./cli.ts --compile --bytecode --format=esm --outfile=mycli bun build ./cli.ts --compile --bytecode --outfile=mycli ``` -The resulting executable contains both the code and bytecode, giving you maximum performance in a single file. +The resulting executable contains both the code and the bytecode. ### ESM bytecode -ESM bytecode requires `--compile` because Bun embeds module metadata (import/export information) in the compiled binary. This metadata allows the JavaScript engine to skip parsing entirely at runtime. +ESM bytecode requires `--compile` because Bun embeds module metadata (import/export information) in the compiled binary. With this metadata, the JavaScript engine skips parsing entirely at runtime. -Without `--compile`, ESM bytecode would still require parsing the source to analyze module dependencies—defeating the purpose of bytecode caching. +Without `--compile`, ESM bytecode would still require parsing the source to analyze module dependencies, which defeats the purpose of bytecode caching. ### Combining with other optimizations -Bytecode works great with minification and source maps: +Combine bytecode with minification and source maps: ```bash terminal icon="terminal" bun build --compile --bytecode --minify --sourcemap ./cli.ts --outfile=mycli @@ -114,12 +114,14 @@ When you update Bun, you must regenerate bytecode: bun build --bytecode ./index.ts --outdir=./dist ``` -If bytecode doesn't match the current Bun version, it's automatically ignored and your code falls back to parsing the JavaScript source. Your app still runs — the performance optimization is skipped. +If bytecode doesn't match the current Bun version, Bun ignores it and falls back to parsing the JavaScript source. **Best practice**: Generate bytecode as part of your CI/CD build process. Don't commit `.jsc` files to git. Regenerate them whenever you update Bun. ### Source code still required +Bytecode doesn't replace your JavaScript. You must deploy both files: + - The `.js` file (your bundled source code) - The `.jsc` file (the bytecode cache) @@ -194,21 +196,21 @@ ls -lh dist/ The `.jsc` file should be 2-8x larger than the `.js` file. -To log if bytecode is being used, set `BUN_JSC_verboseDiskCache=1` in your environment. +To log whether the bytecode is used, set `BUN_JSC_verboseDiskCache=1` in your environment. -On success, it will log something like: +On a cache hit, Bun logs: ```txt [Disk cache] cache hit for sourceCode ``` -If you see a cache miss, it will log something like: +On a cache miss: ```txt [Disk cache] cache miss for sourceCode ``` -It's normal for it it to log a cache miss multiple times since Bun doesn't currently bytecode cache JavaScript code used in builtin modules. +Several cache-miss lines are normal: Bun doesn't bytecode-cache the JavaScript in its builtin modules. ### Common issues @@ -218,7 +220,7 @@ It's normal for it it to log a cache miss multiple times since Bun doesn't curre - Using `--minify` to reduce code size before bytecode generation - Compressing `.jsc` files for network transfer (gzip/brotli) -- Evaluating if the startup performance gain is worth the size increase +- Evaluating whether the startup gain is worth the size increase ## What is bytecode? @@ -230,13 +232,13 @@ When you run JavaScript, the JavaScript engine doesn't execute your source code Bytecode is an intermediate representation - it's lower-level than JavaScript source code, but higher-level than machine code. Think of it as assembly language for a virtual machine. Each bytecode instruction represents a single operation like "load this variable," "add two numbers," or "call this function." -This happens **every single time** you run your code. If you have a CLI tool that runs 100 times a day, your code gets parsed 100 times. If you have a serverless function with frequent cold starts, parsing happens on every cold start. +All of this happens **every time** you run your code. A CLI tool that runs 100 times a day gets parsed 100 times; a serverless function gets parsed on every cold start. With bytecode caching, Bun moves steps 1 and 2 to the build step. At runtime, the engine loads the pre-compiled bytecode and jumps straight to execution. ### Why lazy parsing makes this even better -Modern JavaScript engines use a clever optimization called **lazy parsing**. They don't parse all your code upfront - instead, functions are only parsed when they're first called: +Modern JavaScript engines use an optimization called **lazy parsing**. They don't parse all your code upfront - instead, functions are only parsed when they're first called: ```js // Without bytecode caching: @@ -251,13 +253,13 @@ function main() { } ``` -This means parsing overhead isn't just a startup cost - it happens throughout your application's lifetime as different code paths execute. With bytecode caching, **all functions are pre-compiled**, even the ones that are lazily parsed. The parsing work happens once at build time instead of being distributed throughout your application's execution. +This means parsing overhead isn't just a startup cost - it happens throughout your application's lifetime as different code paths execute. With bytecode caching, **all functions are pre-compiled**, even the ones the engine would otherwise parse lazily. ## The bytecode format ### Inside a .jsc file -A `.jsc` file contains a serialized bytecode structure. Understanding what's inside helps explain both the performance benefits and the file size tradeoff. +A `.jsc` file contains a serialized bytecode structure. **Header section** (validated on every load): @@ -268,18 +270,18 @@ A `.jsc` file contains a serialized bytecode structure. Understanding what's ins - **Source code hash**: A hash of the original JavaScript source code. Bun verifies this matches before using the bytecode. - **Source code length**: The exact length of the source, for additional validation. -- **Compilation flags**: Critical compilation context like strict mode, whether it's a script vs module, eval context type, etc. The same source code compiled with different flags produces different bytecode. +- **Compilation flags**: Compilation context such as strict mode, script vs. module, and eval context type. The same source compiled with different flags produces different bytecode. **Bytecode instructions**: -- **Instruction stream**: The actual bytecode opcodes - the compiled representation of your JavaScript. This is a variable-length sequence of bytecode instructions. -- **Metadata table**: Each opcode has associated metadata - things like profiling counters, type hints, and execution counts (even if not yet populated). +- **Instruction stream**: The bytecode opcodes - the compiled representation of your JavaScript, stored as a variable-length sequence of instructions. +- **Metadata table**: Each opcode has associated metadata such as profiling counters, type hints, and execution counts (even if not yet populated). - **Jump targets**: Pre-computed addresses for control flow (if/else, loops, switch statements). - **Switch tables**: Optimized lookup tables for switch statements. **Constants and identifiers**: -- **Constant pool**: All literal values in your code - numbers, strings, booleans, null, undefined. These are stored as actual JavaScript values (JSValues) so they don't need to be parsed from source at runtime. +- **Constant pool**: All literal values in your code - numbers, strings, booleans, null, undefined. These are stored as JavaScript values (JSValues) so they don't need to be parsed from source at runtime. - **Identifier table**: All variable and function names used in the code. Stored as deduplicated strings. - **Source code representation markers**: Flags indicating how constants should be represented (as integers, doubles, big ints, etc.). @@ -298,17 +300,17 @@ A `.jsc` file contains a serialized bytecode structure. Understanding what's ins ### What bytecode does NOT contain -Importantly, **bytecode does not embed your source code**. Instead: +**Bytecode does not embed your source code**. Instead: - The JavaScript source is stored separately (in the `.js` file) - The bytecode only stores a hash and length of the source - At load time, Bun validates the bytecode matches the current source code -This is why you need to deploy both the `.js` and `.jsc` files. The `.jsc` file is useless without its corresponding `.js` file. +This is why you need to deploy both the `.js` and `.jsc` files: the `.jsc` file is useless without its corresponding `.js` file. ## The tradeoff: file size -Bytecode files are significantly larger than source code - typically 2-8x larger. +Bytecode files are typically 2-8x larger than the source code. ### Why is bytecode so much larger? @@ -361,7 +363,7 @@ Jump targets, switch tables, and exception handler boundaries are all pre-comput ### Mitigation strategies **Compression**: -Bytecode compresses extremely well with gzip/brotli (60-70% compression). The repetitive structure and metadata compress efficiently. +Bytecode compresses well with gzip/brotli (60-70% compression). The repetitive structure and metadata compress efficiently. **Minification first**: Using `--minify` before bytecode generation helps: @@ -390,7 +392,7 @@ The bytecode contains abstract instructions that work on any architecture. Archi Bytecode is **not stable across Bun versions**. Here's why: **Bytecode format changes**: -JavaScriptCore's bytecode format evolves. New opcodes get added, old ones get removed or changed, metadata structures change. Each version of JavaScriptCore has a different bytecode format. +JavaScriptCore's bytecode format changes from version to version. New opcodes get added, old ones get removed or changed, metadata structures change. **Version validation**: The cache version in the `.jsc` file header is a hash of the JavaScriptCore framework. When Bun loads bytecode: @@ -400,14 +402,12 @@ The cache version in the `.jsc` file header is a hash of the JavaScriptCore fram 3. If they don't match, the bytecode is **silently rejected** 4. Bun falls back to parsing the `.js` source code -Your application still runs — the performance optimization is skipped. - **Graceful degradation**: This design means bytecode caching "fails open" - if anything goes wrong (version mismatch, corrupted file, missing file), your code still runs normally. You might see slower startup, but you won't see errors. ## Unlinked vs. linked bytecode -JavaScriptCore makes a crucial distinction between "unlinked" and "linked" bytecode. This separation is what makes bytecode caching possible: +JavaScriptCore distinguishes between "unlinked" and "linked" bytecode. This separation is what makes bytecode caching possible: ### Unlinked bytecode (what's cached) @@ -436,12 +436,10 @@ When Bun runs bytecode, it "links" it - creating a runtime wrapper that adds: - **JIT compilation state**: References to baseline JIT or optimizing JIT (DFG/FTL) compiled versions of hot code. - **Runtime objects**: Pointers to actual JavaScript objects, prototypes, scopes, etc. -This linked representation is created fresh every time you run your code. This allows: +This linked representation is created fresh every time you run your code. This separation allows: 1. **Caching the expensive work** (parsing and compilation to unlinked bytecode) 2. **Still collecting runtime profiling data** to guide optimizations 3. **Still applying JIT optimizations** based on actual execution patterns -Bytecode caching moves expensive work (parsing and compiling to bytecode) from runtime to build time. For applications that start frequently, this can halve your startup time at the cost of larger files on disk. - -For production CLIs and serverless deployments, the combination of `--bytecode --minify --sourcemap` gives you the best performance while maintaining debuggability. +For production CLIs and serverless deployments, the combination of `--bytecode --minify --sourcemap` gives you the best startup time while keeping errors mapped to your original source. diff --git a/docs/bundler/css.mdx b/docs/bundler/css.mdx index 31609aa304fe..48cc445bc097 100644 --- a/docs/bundler/css.mdx +++ b/docs/bundler/css.mdx @@ -8,15 +8,15 @@ Bun's bundler has built-in support for CSS with the following features: - Transpiling modern/future features to work on all browsers (including vendor prefixing) - Minification - CSS Modules -- Tailwind (via a native bundler plugin) +- Tailwind (through a native bundler plugin) ## Transpiling -Bun's CSS bundler lets you use modern/future CSS features without having to worry about browser compatibility — all thanks to its transpiling and vendor prefixing features which are enabled by default. +Transpiling and vendor prefixing are enabled by default, so you can use modern and future CSS features without worrying about browser compatibility. Bun's CSS parser and bundler is a direct port of LightningCSS, with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers. -A huge thanks goes to the amazing work from the authors of LightningCSS and esbuild. +Thanks to the authors of LightningCSS and esbuild for their work. ## Browser Compatibility @@ -32,7 +32,7 @@ By default, Bun's CSS bundler targets the following browsers: ### Nesting -The CSS Nesting specification allows you to write more concise and intuitive stylesheets by nesting selectors inside one another. Instead of repeating parent selectors across your CSS file, you can write child styles directly within their parent blocks. +With CSS Nesting, you write child styles directly inside their parent blocks instead of repeating parent selectors across your CSS file. ```scss title="styles.css" icon="file-code" /* With nesting */ @@ -70,7 +70,7 @@ Bun's CSS bundler automatically converts this nested syntax into traditional fla } ``` -You can also nest media queries and other at-rules inside selectors, eliminating the need to repeat selector patterns: +You can also nest media queries and other at-rules inside selectors: ```scss title="styles.css" icon="file-code" .responsive-element { @@ -98,7 +98,7 @@ This compiles to: ### Color mix -The `color-mix()` function blends two colors together according to a specified ratio in a chosen color space. Use it to create color variations without manually calculating the resulting values. +The `color-mix()` function blends two colors at a given ratio in a chosen color space. Use it to create color variations without calculating the resulting values yourself. ```scss title="styles.css" icon="file-code" .button { @@ -125,11 +125,9 @@ Bun's CSS bundler evaluates these color mixes at build time when all color value } ``` -This feature is particularly useful for creating color systems with programmatically derived shades, tints, and accents without needing preprocessors or custom tooling. - ### Relative colors -CSS allows you to modify individual components of a color using relative color syntax. Create color variations by adjusting specific attributes like lightness, saturation, or individual channels without having to recalculate the entire color. +Relative color syntax modifies individual components of an existing color. Adjust attributes like lightness, saturation, or individual channels without recalculating the entire color. ```css title="styles.css" icon="file-code" .theme-color { @@ -150,11 +148,11 @@ Bun's CSS bundler computes these relative color modifications at build time (whe } ``` -This approach is extremely useful for theme generation, creating accessible color variants, or building color scales based on mathematical relationships instead of hard-coding each value. +Use it for theme generation, accessible color variants, or color scales derived from a base color instead of hard-coding each value. ### LAB colors -Modern CSS supports perceptually uniform color spaces like LAB, LCH, OKLAB, and OKLCH that offer significant advantages over traditional RGB. These color spaces can represent colors outside the standard RGB gamut, resulting in more vibrant and visually consistent designs. +Modern CSS supports the perceptually uniform color spaces LAB, LCH, OKLAB, and OKLCH, which can represent colors outside the standard RGB gamut. ```css title="styles.css" icon="file-code" .vibrant-element { @@ -166,7 +164,7 @@ Modern CSS supports perceptually uniform color spaces like LAB, LCH, OKLAB, and } ``` -Bun's CSS bundler automatically converts these advanced color formats to backwards-compatible alternatives for browsers that don't yet support them: +Bun's CSS bundler converts these color formats to backwards-compatible alternatives for browsers that don't support them: ```css title="styles.css" icon="file-code" .vibrant-element { @@ -182,11 +180,9 @@ Bun's CSS bundler automatically converts these advanced color formats to backwar } ``` -This layered approach ensures optimal color rendering across all browsers while allowing you to use the latest color technologies in your designs. - ### Color function -The `color()` function provides a standardized way to specify colors in various predefined color spaces, expanding your design options beyond the traditional RGB space. This allows you to access wider color gamuts and create more vibrant designs. +The `color()` function specifies colors in predefined color spaces beyond traditional RGB, giving you access to wider color gamuts. ```css title="styles.css" icon="file-code" .vivid-element { @@ -198,7 +194,7 @@ The `color()` function provides a standardized way to specify colors in various } ``` -For browsers that don't support these advanced color functions yet, Bun's CSS bundler provides appropriate RGB fallbacks: +For browsers that don't support these color spaces, Bun's CSS bundler adds RGB fallbacks: ```css title="styles.css" icon="file-code" .vivid-element { @@ -212,11 +208,9 @@ For browsers that don't support these advanced color functions yet, Bun's CSS bu } ``` -This functionality lets you use modern color spaces immediately while ensuring your designs remain functional across all browsers, with optimal colors displayed in supporting browsers and reasonable approximations elsewhere. - ### HWB colors -The HWB (Hue, Whiteness, Blackness) color model expresses colors based on how much white or black is mixed with a pure hue. Many designers find this approach more natural for creating color variations compared to manipulating RGB or HSL values. +The HWB (Hue, Whiteness, Blackness) color model expresses colors based on how much white or black is mixed with a pure hue. This makes tints and shades more direct to create than with RGB or HSL values. ```css title="styles.css" icon="file-code" .easy-theming { @@ -234,7 +228,7 @@ The HWB (Hue, Whiteness, Blackness) color model expresses colors based on how mu } ``` -Bun's CSS bundler automatically converts HWB colors to RGB for compatibility with all browsers: +Bun's CSS bundler converts HWB colors to RGB for compatibility with all browsers: ```css title="styles.css" icon="file-code" .easy-theming { @@ -245,11 +239,9 @@ Bun's CSS bundler automatically converts HWB colors to RGB for compatibility wit } ``` -The HWB model is well-suited for creating systematic color variations for design systems, providing a more direct approach to creating consistent tints and shades than working with RGB or HSL values. - ### Color notation -Modern CSS has introduced more concise ways to express colors. Space-separated color syntax eliminates the need for commas in RGB and HSL values, while hex colors with alpha channels provide a compact way to specify transparency. +Modern CSS supports space-separated RGB and HSL values (no commas) and hex colors with an alpha channel. ```css title="styles.css" icon="file-code" .modern-styling { @@ -267,7 +259,7 @@ Modern CSS has introduced more concise ways to express colors. Space-separated c } ``` -Bun's CSS bundler automatically converts these modern color formats to ensure compatibility with older browsers: +Bun's CSS bundler converts these formats for older browsers: ```css title="styles.css" icon="file-code" .modern-styling { @@ -284,11 +276,9 @@ Bun's CSS bundler automatically converts these modern color formats to ensure co } ``` -This conversion process lets you write cleaner, more modern CSS while ensuring your styles work correctly across all browsers. - ### light-dark() color function -The `light-dark()` function implements color schemes that respect the user's system preference without requiring media queries. This function accepts two color values and automatically selects the appropriate one based on the current color scheme context. +The `light-dark()` function takes two colors and applies one based on the current color scheme, so styles respect the user's system preference without media queries. ```css title="styles.css" icon="file-code" :root { @@ -313,7 +303,7 @@ The `light-dark()` function implements color schemes that respect the user's sys } ``` -For browsers that don't support this feature yet, Bun's CSS bundler converts it to use CSS variables with proper fallbacks: +For browsers that don't support `light-dark()`, Bun's CSS bundler converts it to CSS variables with fallbacks: ```css title="styles.css" icon="file-code" :root { @@ -348,11 +338,9 @@ For browsers that don't support this feature yet, Bun's CSS bundler converts it } ``` -This approach gives you a clean way to handle light and dark themes without duplicating styles or writing complex media queries, while maintaining compatibility with browsers that don't yet support the feature natively. - ### Logical properties -CSS logical properties let you define layout, spacing, and sizing relative to the document's writing mode and text direction rather than physical screen directions. This is crucial for creating truly international layouts that automatically adapt to different writing systems. +CSS logical properties define layout, spacing, and sizing relative to the document's writing mode and text direction rather than physical screen directions, so layouts adapt to different writing systems. ```css title="styles.css" icon="file-code" .multilingual-component { @@ -371,7 +359,7 @@ CSS logical properties let you define layout, spacing, and sizing relative to th } ``` -For browsers that don't fully support logical properties, Bun's CSS bundler compiles them to physical properties with appropriate directional adjustments: +For browsers that don't fully support logical properties, Bun's CSS bundler compiles them to physical properties for each text direction: ```css title="styles.css" icon="file-code" /* For left-to-right languages */ @@ -395,11 +383,11 @@ For browsers that don't fully support logical properties, Bun's CSS bundler comp } ``` -If the `:dir()` selector isn't supported, additional fallbacks are automatically generated to ensure your layouts work properly across all browsers and writing systems. This makes creating internationalized designs much simpler while maintaining compatibility with older browsers. +If the `:dir()` selector isn't supported, Bun generates additional fallbacks. ### :dir() selector -The `:dir()` pseudo-class selector allows you to style elements based on their text direction (RTL or LTR), letting you create direction-aware designs without JavaScript. This selector matches elements based on their directionality as determined by the document or explicit direction attributes. +The `:dir()` pseudo-class styles elements based on their text direction (RTL or LTR), as determined by the document or explicit direction attributes. Use it to write direction-aware styles without JavaScript. ```css title="styles.css" icon="file-code" /* Apply different styles based on text direction */ @@ -421,7 +409,7 @@ The `:dir()` pseudo-class selector allows you to style elements based on their t } ``` -For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler converts it to the more widely supported `:lang()` selector with appropriate language mappings: +For browsers that don't support the `:dir()` selector, Bun's CSS bundler converts it to the more widely supported `:lang()` selector with appropriate language mappings: ```css title="styles.css" icon="file-code" /* Converted to use language-based selectors as fallback */ @@ -442,11 +430,11 @@ For browsers that don't support the `:dir()` selector yet, Bun's CSS bundler con } ``` -This conversion lets you write direction-aware CSS that works reliably across browsers, even those that don't yet support the `:dir()` selector natively. If multiple arguments to `:lang()` aren't supported, further fallbacks are automatically provided. +If multiple arguments to `:lang()` aren't supported, Bun generates further fallbacks. ### :lang() selector -The `:lang()` pseudo-class selector targets elements based on the language they're in, enabling language-specific styling. Modern CSS supports passing multiple language codes to `:lang()`, letting you group language-specific rules more efficiently. +The `:lang()` pseudo-class targets elements based on their language. To group rules for related languages, pass multiple language codes to a single `:lang()`. ```css title="styles.css" icon="file-code" /* Typography adjustments for CJK languages */ @@ -465,7 +453,7 @@ blockquote:lang(de, nl, da, sv) { } ``` -For browsers that don't support multiple arguments in the `:lang()` selector, Bun's CSS bundler converts this syntax to use the `:is()` selector to maintain the same behavior: +For browsers that don't support multiple arguments in the `:lang()` selector, Bun's CSS bundler converts this syntax to the `:is()` selector with the same behavior: ```css title="styles.css" icon="file-code" /* Multiple languages grouped with :is() for better browser support */ @@ -483,11 +471,11 @@ blockquote:is(:lang(de), :lang(nl), :lang(da), :lang(sv)) { } ``` -If needed, Bun can provide additional fallbacks for `:is()` as well, ensuring your language-specific styles work across all browsers. This approach simplifies creating internationalized designs with distinct typographic and styling rules for different language groups. +If needed, Bun can generate additional fallbacks for `:is()` as well. ### :is() selector -The `:is()` pseudo-class function (formerly `:matches()`) allows you to create more concise and readable selectors by grouping multiple selectors together. It accepts a selector list as its argument and matches if any of the selectors in that list match, significantly reducing repetition in your CSS. +The `:is()` pseudo-class function (formerly `:matches()`) takes a selector list and matches if any selector in the list matches. ```css title="styles.css" icon="file-code" /* Instead of writing these separately */ @@ -543,14 +531,13 @@ For browsers that don't support `:is()`, Bun's CSS bundler provides fallbacks us ``` - The vendor-prefixed versions have some limitations compared to the standardized `:is()` selector, particularly with - complex selectors. Bun handles these limitations intelligently, only using prefixed versions when they'll work - correctly. + The vendor-prefixed versions have limitations compared to the standardized `:is()` selector, particularly with complex + selectors. Bun only uses the prefixed versions when they work correctly. ### :not() selector -The `:not()` pseudo-class allows you to exclude elements that match a specific selector. The modern version of this selector accepts multiple arguments, letting you exclude multiple patterns with a single, concise selector. +The `:not()` pseudo-class excludes elements that match a selector. The modern version accepts multiple arguments to exclude several patterns with one `:not()`. ```css title="styles.css" icon="file-code" /* Select all buttons except primary and secondary variants */ @@ -565,7 +552,7 @@ h2:not(.sidebar *, footer *) { } ``` -For browsers that don't support multiple arguments in `:not()`, Bun's CSS bundler converts this syntax to a more compatible form while preserving the same behavior: +For browsers that don't support multiple arguments in `:not()`, Bun's CSS bundler converts this syntax to a more compatible form with the same behavior: ```css title="styles.css" icon="file-code" /* Converted to use :not with :is() for compatibility */ @@ -599,11 +586,11 @@ button:not(:is(.primary, .secondary)) { } ``` -This conversion ensures your negative selectors work correctly across all browsers while maintaining the correct specificity and behavior of the original selector. +The converted selectors keep the specificity and behavior of the original. ### Math functions -CSS now includes a rich set of mathematical functions that let you perform complex calculations directly in your stylesheets. These include standard math functions (`round()`, `mod()`, `rem()`, `abs()`, `sign()`), trigonometric functions (`sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, `atan2()`), and exponential functions (`pow()`, `sqrt()`, `exp()`, `log()`, `hypot()`). +CSS includes standard math functions (`round()`, `mod()`, `rem()`, `abs()`, `sign()`), trigonometric functions (`sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, `atan2()`), and exponential functions (`pow()`, `sqrt()`, `exp()`, `log()`, `hypot()`). ```css title="styles.css" icon="file-code" .dynamic-sizing { @@ -622,7 +609,7 @@ CSS now includes a rich set of mathematical functions that let you perform compl } ``` -Bun's CSS bundler evaluates these mathematical expressions at build time when all values are known constants (not variables), resulting in optimized output: +Bun's CSS bundler evaluates these expressions at build time when all values are known constants (not variables): ```css title="styles.css" icon="file-code" .dynamic-sizing { @@ -634,11 +621,9 @@ Bun's CSS bundler evaluates these mathematical expressions at build time when al } ``` -This approach lets you write more expressive and maintainable CSS with meaningful mathematical relationships, which then gets compiled to optimized values for maximum browser compatibility and performance. - ### Media query ranges -Modern CSS supports range syntax for media queries, allowing you to specify breakpoints using comparison operators like `<`, `>`, `<=`, and `>=` instead of the more verbose `min-` and `max-` prefixes. This syntax is more readable and matches how you typically think about values and ranges. +Media query range syntax expresses breakpoints with comparison operators (`<`, `>`, `<=`, `>=`) instead of the more verbose `min-` and `max-` prefixes. ```css title="styles.css" icon="file-code" /* Modern syntax with comparison operators */ @@ -663,7 +648,7 @@ Modern CSS supports range syntax for media queries, allowing you to specify brea } ``` -Bun's CSS bundler converts these modern range queries to traditional media query syntax for compatibility with all browsers: +Bun's CSS bundler converts range queries to traditional media query syntax for compatibility with all browsers: ```css title="styles.css" icon="file-code" /* Converted to traditional min/max syntax */ @@ -686,11 +671,9 @@ Bun's CSS bundler converts these modern range queries to traditional media query } ``` -This lets you write more readable media queries while ensuring your stylesheets work correctly across all browsers, including those that don't support the modern range syntax. - ### Shorthands -CSS has introduced several modern shorthand properties that improve code readability and maintainability. Bun's CSS bundler ensures these convenient shorthands work on all browsers by converting them to their longhand equivalents when needed. +CSS has introduced several shorthand properties that combine multiple longhand properties. ```css title="styles.css" icon="file-code" /* Alignment shorthands */ @@ -726,7 +709,7 @@ CSS has introduced several modern shorthand properties that improve code readabi } ``` -For browsers that don't support these modern shorthands, Bun converts them to their component longhand properties: +For browsers that don't support these shorthands, Bun converts them to their component longhand properties: ```css title="styles.css" icon="file-code" .flex-container { @@ -763,11 +746,9 @@ For browsers that don't support these modern shorthands, Bun converts them to th } ``` -This conversion ensures your stylesheets remain clean and maintainable while providing the broadest possible browser compatibility. - ### Double position gradients -The double position gradient syntax is a modern CSS feature that allows you to create hard color stops in gradients by specifying the same color at two adjacent positions. This creates a sharp transition rather than a smooth fade, which is useful for creating stripes, color bands, and other multi-color designs. +Double position gradient syntax specifies the same color at two adjacent positions to create a hard color stop: a sharp transition instead of a smooth fade. Use it for stripes, color bands, and other multi-color designs. ```css title="styles.css" icon="file-code" .striped-background { @@ -796,7 +777,7 @@ The double position gradient syntax is a modern CSS feature that allows you to c } ``` -For browsers that don't support this syntax, Bun's CSS bundler automatically converts it to the traditional format by duplicating color stops: +For browsers that don't support this syntax, Bun's CSS bundler converts it to the traditional format by duplicating color stops: ```css title="styles.css" icon="file-code" .striped-background { @@ -827,11 +808,9 @@ For browsers that don't support this syntax, Bun's CSS bundler automatically con } ``` -This conversion lets you use the cleaner double position syntax in your source code while ensuring gradients display correctly in all browsers. - ### system-ui font -The `system-ui` generic font family lets you use the device's native UI font, creating interfaces that feel more integrated with the operating system. This provides a more native look and feel without having to specify different font stacks for each platform. +The `system-ui` generic font family uses the device's native UI font. ```css title="styles.css" icon="file-code" .native-interface { @@ -845,7 +824,7 @@ The `system-ui` generic font family lets you use the device's native UI font, cr } ``` -For browsers that don't support `system-ui`, Bun's CSS bundler automatically expands it to a comprehensive cross-platform font stack: +For browsers that don't support `system-ui`, Bun's CSS bundler expands it to a cross-platform font stack: ```css title="styles.css" icon="file-code" .native-interface { @@ -878,20 +857,20 @@ For browsers that don't support `system-ui`, Bun's CSS bundler automatically exp } ``` -This approach gives you the simplicity of writing just `system-ui` in your source code while ensuring your interface adapts correctly to all operating systems and browsers. The expanded font stack includes appropriate system fonts for macOS/iOS, Windows, Android, Linux, and fallbacks for older browsers. +The expanded stack includes system fonts for macOS/iOS, Windows, Android, and Linux, plus fallbacks for older browsers. ## CSS Modules -Bun's bundler also supports bundling CSS modules in addition to regular CSS with support for the following features: +Bun's bundler also supports CSS modules, with the following features: -- Automatically detecting CSS module files (`.module.css`) with zero configuration +- Detecting CSS module files (`.module.css`) with no configuration - Composition (`composes` property) - Importing CSS modules into JSX/TSX - Warnings/errors for invalid usages of CSS modules -A CSS module is a CSS file (with the `.module.css` extension) where are all class names and animations are scoped to the file. This helps you avoid class name collisions as CSS declarations are globally scoped by default. +A CSS module is a CSS file (with the `.module.css` extension) where all class names and animations are scoped to the file. This helps you avoid class name collisions, as CSS declarations are globally scoped by default. -Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers. +Bun's bundler transforms locally scoped class names into unique identifiers. ### Getting started @@ -925,7 +904,7 @@ export default function App() { } ``` -The styles object from importing the CSS module file will be an object with all class names as keys and their unique identifiers as values: +Importing a CSS module gives you an object that maps each class name to its unique identifier: ```ts title="app.tsx" icon="/icons/typescript.svg" import styles from "./styles.module.css"; @@ -935,7 +914,7 @@ console.log(styles); console.log(otherStyles); ``` -This will output: +This outputs: ```ts title="app.tsx" icon="/icons/typescript.svg" { @@ -947,11 +926,11 @@ This will output: } ``` -As you can see, the class names are unique to each file, avoiding any collisions! +The class names are unique to each file, so they don't collide. ### Composition -CSS modules allow you to compose class selectors together. This lets you reuse style rules across multiple classes. +CSS modules can compose class selectors together to reuse style rules across multiple classes. For example: @@ -966,7 +945,7 @@ For example: } ``` -Would be the same as writing: +This is the same as writing: ```css title="styles.module.css" icon="file-code" .button { @@ -979,7 +958,7 @@ Would be the same as writing: } ``` -There are a couple rules to keep in mind when using `composes`: +Two rules apply when using `composes`: **Composition Rules:** - A `composes` property must come before any regular CSS properties or declarations - You can @@ -1017,8 +996,8 @@ You can also compose from a separate CSS module file: ``` -When composing classes from separate files, be sure that they do not contain the same properties. +When composing classes from separate files, make sure they do not contain the same properties. -The CSS module spec says that composing classes from separate files with conflicting properties is undefined behavior, meaning that the output may differ and be unreliable. +The CSS module spec says that composing classes from separate files with conflicting properties is undefined behavior: the output may differ and be unreliable. diff --git a/docs/bundler/esbuild.mdx b/docs/bundler/esbuild.mdx index aece456479d5..7e1667983804 100644 --- a/docs/bundler/esbuild.mdx +++ b/docs/bundler/esbuild.mdx @@ -3,31 +3,28 @@ title: esbuild description: Migration guide from esbuild to Bun's bundler --- -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. +Bun's bundler API is heavily inspired by esbuild. This page is a side-by-side comparison of the two APIs. -There are a few behavioral differences to note. +A few behaviors differ: - **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`. + **Bundling by default.** Unlike esbuild, Bun bundles by default; no `--bundle` flag is needed. To transpile each file + individually, use `Bun.Transpiler`. - **Bundler only.** Unlike esbuild, Bun's bundler does not include a built-in development server or file watcher. 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. + **Bundler only.** Unlike esbuild, Bun's bundler has no built-in development server or file watcher. Use it with + `Bun.serve` and other runtime APIs to get the same effect. esbuild's HTTP and file-watching options don't apply. ## Performance -With a performance-minded API coupled with the extensively optimized Rust-based JS/TS parser, Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark. +Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark. Bundling 10 copies of three.js from scratch, with sourcemaps and minification ## CLI API -Bun and esbuild both provide a command-line interface. - ```bash terminal icon="terminal" # esbuild esbuild --outdir=out --bundle @@ -36,152 +33,152 @@ esbuild --outdir=out --bundle bun build --outdir=out ``` -In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Other flags like `--outdir ` 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`. - -| esbuild | bun build | Notes | -| ---------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--bundle` | n/a | Bun always bundles, use `--no-bundle` to disable this behavior. | -| `--define:K=V` | `--define K=V` | Small syntax difference; no colon.
`esbuild --define:foo=bar`
`bun build --define foo=bar` | -| `--external:` | `--external ` | Small syntax difference; no colon.
`esbuild --external:react`
`bun build --external react` | -| `--format` | `--format` | Bun supports `"esm"` and `"cjs"` currently, but more module formats are planned. esbuild defaults to `"iife"`. | -| `--loader:.ext=loader` | `--loader .ext:loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented.

The syntax for `--loader` is slightly different.
`esbuild app.ts --bundle --loader:.svg=text`
`bun build app.ts --loader .svg:text` | -| `--minify` | `--minify` | No differences | -| `--outdir` | `--outdir` | No differences | -| `--outfile` | `--outfile` | No differences | -| `--packages` | `--packages` | No differences | -| `--platform` | `--target` | Renamed to `--target` for consistency with tsconfig. Does not support `neutral`. | -| `--serve` | n/a | Not applicable | -| `--sourcemap` | `--sourcemap` | No differences | -| `--splitting` | `--splitting` | No differences | -| `--target` | n/a | Not supported. Bun's bundler performs no syntactic down-leveling at this time. | -| `--watch` | `--watch` | No differences | -| `--allow-overwrite` | n/a | Overwriting is never allowed | -| `--analyze` | n/a | Not supported | -| `--asset-names` | `--asset-naming` | Renamed for consistency with naming in JS API | -| `--banner` | `--banner` | Only applies to js bundles | -| `--footer` | `--footer` | Only applies to js bundles | -| `--certfile` | n/a | Not applicable | -| `--charset=utf8` | n/a | Not supported | -| `--chunk-names` | `--chunk-naming` | Renamed for consistency with naming in JS API | -| `--color` | n/a | Always enabled | -| `--drop` | `--drop` | | -| n/a | `--feature` | Bun-specific. Enable feature flags for compile-time dead-code elimination via `import { feature } from "bun:bundle"` | -| `--entry-names` | `--entry-naming` | Renamed for consistency with naming in JS API | -| `--global-name` | n/a | Not applicable, Bun does not support `iife` output at this time | -| `--ignore-annotations` | `--ignore-dce-annotations` | | -| `--inject` | n/a | Not supported | -| `--jsx` | `--jsx-runtime ` | Supports `"automatic"` (uses jsx transform) and `"classic"` (uses `React.createElement`) | -| `--jsx-dev` | n/a | Bun reads `compilerOptions.jsx` from `tsconfig.json` to determine a default. If `compilerOptions.jsx` is `"react-jsx"`, or if `NODE_ENV=production`, Bun will use the jsx transform. Otherwise, it uses `jsxDEV`. The bundler does not support `preserve`. | -| `--jsx-factory` | `--jsx-factory` | | -| `--jsx-fragment` | `--jsx-fragment` | | -| `--jsx-import-source` | `--jsx-import-source` | | -| `--jsx-side-effects` | n/a | JSX is always assumed to be side-effect-free | -| `--keep-names` | n/a | Not supported | -| `--keyfile` | n/a | Not applicable | -| `--legal-comments` | n/a | Not supported | -| `--log-level` | n/a | Not supported. This can be set in `bunfig.toml` as `logLevel`. | -| `--log-limit` | n/a | Not supported | -| `--log-override:X=Y` | n/a | Not supported | -| `--main-fields` | n/a | Not supported | -| `--mangle-cache` | n/a | Not supported | -| `--mangle-props` | n/a | Not supported | -| `--mangle-quoted` | n/a | Not supported | -| `--metafile` | n/a | Not supported | -| `--minify-whitespace` | `--minify-whitespace` | | -| `--minify-identifiers` | `--minify-identifiers` | | -| `--minify-syntax` | `--minify-syntax` | | -| `--out-extension` | n/a | Not supported | -| `--outbase` | `--root` | | -| `--preserve-symlinks` | n/a | Not supported | -| `--public-path` | `--public-path` | | -| `--pure` | n/a | Not supported | -| `--reserve-props` | n/a | Not supported | -| `--resolve-extensions` | n/a | Not supported | -| `--servedir` | n/a | Not applicable | -| `--source-root` | n/a | Not supported | -| `--sourcefile` | n/a | Not supported. Bun does not support stdin input yet. | -| `--sourcemap` | `--sourcemap` | No differences | -| `--sources-content` | n/a | Not supported | -| `--supported` | n/a | Not supported | -| `--tree-shaking` | n/a | Always true | -| `--tsconfig` | `--tsconfig-override` | | -| `--version` | n/a | Run `bun --version` to see the version of Bun. | +In Bun's CLI, boolean flags like `--minify` take no argument. Flags that take one, like `--outdir `, can be written as `--outdir out` or `--outdir=out`. Some flags, like `--define`, can be repeated: `--define foo=bar --define bar=baz`. + +| esbuild | bun build | Notes | +| ---------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--bundle` | n/a | Bun always bundles; use `--no-bundle` to disable it. | +| `--define:K=V` | `--define K=V` | Small syntax difference; no colon.
`esbuild --define:foo=bar`
`bun build --define foo=bar` | +| `--external:` | `--external ` | Small syntax difference; no colon.
`esbuild --external:react`
`bun build --external react` | +| `--format` | `--format` | Bun supports `"esm"` and `"cjs"`; more module formats are planned. esbuild defaults to `"iife"`. | +| `--loader:.ext=loader` | `--loader .ext:loader` | Bun supports a different set of built-in loaders than esbuild; see [loaders](/bundler/loaders). The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not implemented.

The syntax for `--loader` differs.
`esbuild app.ts --bundle --loader:.svg=text`
`bun build app.ts --loader .svg:text` | +| `--minify` | `--minify` | No differences | +| `--outdir` | `--outdir` | No differences | +| `--outfile` | `--outfile` | No differences | +| `--packages` | `--packages` | No differences | +| `--platform` | `--target` | Renamed to `--target` for consistency with tsconfig. Does not support `neutral`. | +| `--serve` | n/a | Not applicable | +| `--sourcemap` | `--sourcemap` | No differences | +| `--splitting` | `--splitting` | No differences | +| `--target` | n/a | Not supported. Bun's bundler performs no syntactic down-leveling. | +| `--watch` | `--watch` | No differences | +| `--allow-overwrite` | n/a | Overwriting is never allowed | +| `--analyze` | n/a | Not supported | +| `--asset-names` | `--asset-naming` | Renamed for consistency with naming in JS API | +| `--banner` | `--banner` | Only applies to js bundles | +| `--footer` | `--footer` | Only applies to js bundles | +| `--certfile` | n/a | Not applicable | +| `--charset=utf8` | n/a | Not supported | +| `--chunk-names` | `--chunk-naming` | Renamed for consistency with naming in JS API | +| `--color` | n/a | Always enabled | +| `--drop` | `--drop` | | +| n/a | `--feature` | Bun-specific. Enables feature flags for compile-time dead-code elimination through `import { feature } from "bun:bundle"` | +| `--entry-names` | `--entry-naming` | Renamed for consistency with naming in JS API | +| `--global-name` | n/a | Not applicable; Bun does not support `iife` output | +| `--ignore-annotations` | `--ignore-dce-annotations` | | +| `--inject` | n/a | Not supported | +| `--jsx` | `--jsx-runtime ` | Supports `"automatic"` (uses jsx transform) and `"classic"` (uses `React.createElement`) | +| `--jsx-dev` | n/a | Bun reads `compilerOptions.jsx` from `tsconfig.json` to determine a default. If `compilerOptions.jsx` is `"react-jsx"`, or if `NODE_ENV=production`, Bun uses the jsx transform. Otherwise, it uses `jsxDEV`. The bundler does not support `preserve`. | +| `--jsx-factory` | `--jsx-factory` | | +| `--jsx-fragment` | `--jsx-fragment` | | +| `--jsx-import-source` | `--jsx-import-source` | | +| `--jsx-side-effects` | n/a | JSX is always assumed to be side-effect-free | +| `--keep-names` | n/a | Not supported | +| `--keyfile` | n/a | Not applicable | +| `--legal-comments` | n/a | Not supported | +| `--log-level` | n/a | Not supported. This can be set in `bunfig.toml` as `logLevel`. | +| `--log-limit` | n/a | Not supported | +| `--log-override:X=Y` | n/a | Not supported | +| `--main-fields` | n/a | Not supported | +| `--mangle-cache` | n/a | Not supported | +| `--mangle-props` | n/a | Not supported | +| `--mangle-quoted` | n/a | Not supported | +| `--metafile` | n/a | Not supported | +| `--minify-whitespace` | `--minify-whitespace` | | +| `--minify-identifiers` | `--minify-identifiers` | | +| `--minify-syntax` | `--minify-syntax` | | +| `--out-extension` | n/a | Not supported | +| `--outbase` | `--root` | | +| `--preserve-symlinks` | n/a | Not supported | +| `--public-path` | `--public-path` | | +| `--pure` | n/a | Not supported | +| `--reserve-props` | n/a | Not supported | +| `--resolve-extensions` | n/a | Not supported | +| `--servedir` | n/a | Not applicable | +| `--source-root` | n/a | Not supported | +| `--sourcefile` | n/a | Not supported. Bun does not support stdin input. | +| `--sourcemap` | `--sourcemap` | No differences | +| `--sources-content` | n/a | Not supported | +| `--supported` | n/a | Not supported | +| `--tree-shaking` | n/a | Always true | +| `--tsconfig` | `--tsconfig-override` | | +| `--version` | n/a | Run `bun --version` to see the version of Bun. | ## JavaScript API -| esbuild.build() | Bun.build() | Notes | -| ------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `absWorkingDir` | n/a | Always set to `process.cwd()` | -| `alias` | n/a | Not supported | -| `allowOverwrite` | n/a | Always false | -| `assetNames` | `naming.asset` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
naming: {
asset: "[name].[ext]",
},
});
` | -| `banner` | n/a | Not supported | -| `bundle` | n/a | Always true. Use `Bun.Transpiler` to transpile without bundling. | -| `charset` | n/a | Not supported | -| `chunkNames` | `naming.chunk` | Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
naming: {
chunk: "[name].[ext]",
},
});
` | -| `color` | n/a | Bun returns logs in the `logs` property of the build result. | -| `conditions` | n/a | Not supported. Export conditions priority is determined by `target`. | -| `define` | `define` | | -| `drop` | n/a | Not supported | -| `entryNames` | `naming` or `naming.entry` | Bun supports a `naming` key that can either be a string or an object. Uses same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
// when string, this is equivalent to entryNames
naming: "[name].[ext]",

// granular naming options
naming: {
entry: "[name].[ext]",
asset: "[name].[ext]",
chunk: "[name].[ext]",
},
});
` | -| `entryPoints` | `entrypoints` | Capitalization difference | -| `external` | `external` | No differences | -| `footer` | n/a | Not supported | -| `format` | `format` | Only supports `"esm"` currently. Support for `"cjs"` and `"iife"` is planned. | -| `globalName` | n/a | Not supported | -| `ignoreAnnotations` | n/a | Not supported | -| `inject` | n/a | Not supported | -| `jsx` | `jsx` | Not supported in JS API, configure in `tsconfig.json` | -| `jsxDev` | `jsxDev` | Not supported in JS API, configure in `tsconfig.json` | -| `jsxFactory` | `jsxFactory` | Not supported in JS API, configure in `tsconfig.json` | -| `jsxFragment` | `jsxFragment` | Not supported in JS API, configure in `tsconfig.json` | -| `jsxImportSource` | `jsxImportSource` | Not supported in JS API, configure in `tsconfig.json` | -| `jsxSideEffects` | `jsxSideEffects` | Not supported in JS API, configure in `tsconfig.json` | -| `keepNames` | n/a | Not supported | -| `legalComments` | n/a | Not supported | -| `loader` | `loader` | Bun supports a different set of built-in loaders than esbuild; see Bundler > Loaders for a complete reference. The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not yet implemented. | -| `logLevel` | n/a | Not supported | -| `logLimit` | n/a | Not supported | -| `logOverride` | n/a | Not supported | -| `mainFields` | n/a | Not supported | -| `mangleCache` | n/a | Not supported | -| `mangleProps` | n/a | Not supported | -| `mangleQuoted` | n/a | Not supported | -| `metafile` | n/a | Not supported | -| `minify` | `minify` | In Bun, `minify` can be a boolean or an object.

`ts
await Bun.build({
entrypoints: ['./index.tsx'],
// enable all minification
minify: true

// granular options
minify: {
identifiers: true,
syntax: true,
whitespace: true
}
})
` | -| `minifyIdentifiers` | `minify.identifiers` | See `minify` | -| `minifySyntax` | `minify.syntax` | See `minify` | -| `minifyWhitespace` | `minify.whitespace` | See `minify` | -| `nodePaths` | n/a | Not supported | -| `outExtension` | n/a | Not supported | -| `outbase` | `root` | Different name | -| `outdir` | `outdir` | No differences | -| `outfile` | `outfile` | No differences | -| `packages` | n/a | Not supported, use `external` | -| `platform` | `target` | Supports `"bun"`, `"node"` and `"browser"` (the default). Does not support `"neutral"`. | -| `plugins` | `plugins` | Bun's plugin API is a subset of esbuild's. Some esbuild plugins will work out of the box with Bun. | -| `preserveSymlinks` | n/a | Not supported | -| `publicPath` | `publicPath` | No differences | -| `pure` | n/a | Not supported | -| `reserveProps` | n/a | Not supported | -| `resolveExtensions` | n/a | Not supported | -| `sourceRoot` | n/a | Not supported | -| `sourcemap` | `sourcemap` | Supports `"inline"`, `"external"`, and `"none"` | -| `sourcesContent` | n/a | Not supported | -| `splitting` | `splitting` | No differences | -| `stdin` | n/a | Not supported | -| `supported` | n/a | Not supported | -| `target` | n/a | No support for syntax downleveling | -| `treeShaking` | n/a | Always true | -| `tsconfig` | n/a | Not supported | -| `write` | n/a | Set to true if `outdir`/`outfile` is set, otherwise false | +| esbuild.build() | Bun.build() | Notes | +| ------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `absWorkingDir` | n/a | Always set to `process.cwd()` | +| `alias` | n/a | Not supported | +| `allowOverwrite` | n/a | Always false | +| `assetNames` | `naming.asset` | Uses the same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
naming: {
asset: "[name].[ext]",
},
});
` | +| `banner` | n/a | Not supported | +| `bundle` | n/a | Always true. Use `Bun.Transpiler` to transpile without bundling. | +| `charset` | n/a | Not supported | +| `chunkNames` | `naming.chunk` | Uses the same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
naming: {
chunk: "[name].[ext]",
},
});
` | +| `color` | n/a | Bun returns logs in the `logs` property of the build result. | +| `conditions` | n/a | Not supported. Export conditions priority is determined by `target`. | +| `define` | `define` | | +| `drop` | n/a | Not supported | +| `entryNames` | `naming` or `naming.entry` | Bun supports a `naming` key that can either be a string or an object. Uses the same templating syntax as esbuild, but `[ext]` must be included explicitly.

`ts
Bun.build({
entrypoints: ["./index.tsx"],
// when string, this is equivalent to entryNames
naming: "[name].[ext]",

// granular naming options
naming: {
entry: "[name].[ext]",
asset: "[name].[ext]",
chunk: "[name].[ext]",
},
});
` | +| `entryPoints` | `entrypoints` | Capitalization difference | +| `external` | `external` | No differences | +| `footer` | n/a | Not supported | +| `format` | `format` | Only supports `"esm"`. Support for `"cjs"` and `"iife"` is planned. | +| `globalName` | n/a | Not supported | +| `ignoreAnnotations` | n/a | Not supported | +| `inject` | n/a | Not supported | +| `jsx` | `jsx` | Not supported in the JS API; configure in `tsconfig.json` | +| `jsxDev` | `jsxDev` | Not supported in the JS API; configure in `tsconfig.json` | +| `jsxFactory` | `jsxFactory` | Not supported in the JS API; configure in `tsconfig.json` | +| `jsxFragment` | `jsxFragment` | Not supported in the JS API; configure in `tsconfig.json` | +| `jsxImportSource` | `jsxImportSource` | Not supported in the JS API; configure in `tsconfig.json` | +| `jsxSideEffects` | `jsxSideEffects` | Not supported in the JS API; configure in `tsconfig.json` | +| `keepNames` | n/a | Not supported | +| `legalComments` | n/a | Not supported | +| `loader` | `loader` | Bun supports a different set of built-in loaders than esbuild; see [loaders](/bundler/loaders). The esbuild loaders `dataurl`, `binary`, `base64`, `copy`, and `empty` are not implemented. | +| `logLevel` | n/a | Not supported | +| `logLimit` | n/a | Not supported | +| `logOverride` | n/a | Not supported | +| `mainFields` | n/a | Not supported | +| `mangleCache` | n/a | Not supported | +| `mangleProps` | n/a | Not supported | +| `mangleQuoted` | n/a | Not supported | +| `metafile` | n/a | Not supported | +| `minify` | `minify` | In Bun, `minify` can be a boolean or an object.

`ts
await Bun.build({
entrypoints: ['./index.tsx'],
// enable all minification
minify: true

// granular options
minify: {
identifiers: true,
syntax: true,
whitespace: true
}
})
` | +| `minifyIdentifiers` | `minify.identifiers` | See `minify` | +| `minifySyntax` | `minify.syntax` | See `minify` | +| `minifyWhitespace` | `minify.whitespace` | See `minify` | +| `nodePaths` | n/a | Not supported | +| `outExtension` | n/a | Not supported | +| `outbase` | `root` | Different name | +| `outdir` | `outdir` | No differences | +| `outfile` | `outfile` | No differences | +| `packages` | n/a | Not supported, use `external` | +| `platform` | `target` | Supports `"bun"`, `"node"` and `"browser"` (the default). Does not support `"neutral"`. | +| `plugins` | `plugins` | Bun's plugin API is a subset of esbuild's. Some esbuild plugins work with Bun without modification. | +| `preserveSymlinks` | n/a | Not supported | +| `publicPath` | `publicPath` | No differences | +| `pure` | n/a | Not supported | +| `reserveProps` | n/a | Not supported | +| `resolveExtensions` | n/a | Not supported | +| `sourceRoot` | n/a | Not supported | +| `sourcemap` | `sourcemap` | Supports `"inline"`, `"external"`, and `"none"` | +| `sourcesContent` | n/a | Not supported | +| `splitting` | `splitting` | No differences | +| `stdin` | n/a | Not supported | +| `supported` | n/a | Not supported | +| `target` | n/a | No support for syntax downleveling | +| `treeShaking` | n/a | Always true | +| `tsconfig` | n/a | Not supported | +| `write` | n/a | Set to true if `outdir`/`outfile` is set, otherwise false | ## 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. +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, and many third-party esbuild plugins work with Bun without modification. - Long term, we aim for feature parity with esbuild's API, so if something doesn't work please file an issue to help us + Long term, we aim for feature parity with esbuild's API. If something doesn't work, file an issue to help us prioritize. @@ -198,7 +195,7 @@ const myPlugin: BunPlugin = { }; ``` -The builder object provides some methods for hooking into parts of the bundling process. Bun implements `onStart`, `onEnd`, `onResolve`, and `onLoad`. It does not yet implement the esbuild hooks `onDispose` and `resolve`. `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. +The builder object's methods hook into parts of the bundling process. Bun implements `onStart`, `onEnd`, `onResolve`, and `onLoad`; it does not implement the esbuild hooks `onDispose` and `resolve`. `initialOptions` is partially implemented: it's read-only and exposes only a subset of esbuild's options. Use `config` (the same thing in Bun's `BuildConfig` format) instead. ```ts title="myPlugin.ts" icon="/icons/typescript.svg" import type { BunPlugin } from "bun"; diff --git a/docs/bundler/executables.mdx b/docs/bundler/executables.mdx index a7f9650764b6..547af02a10ca 100644 --- a/docs/bundler/executables.mdx +++ b/docs/bundler/executables.mdx @@ -27,7 +27,7 @@ Bun's bundler implements a `--compile` flag for generating a standalone binary f console.log("Hello world!"); ``` -This bundles `cli.ts` into an executable that can be executed directly: +This bundles `cli.ts` into an executable you can run directly: ```bash terminal icon="terminal" ./mycli @@ -43,7 +43,7 @@ All imported files and packages are bundled into the executable, along with a co ## Cross-compile to other platforms -The `--target` flag lets you compile your standalone executable for a different operating system, architecture, or version of Bun than the machine you're running `bun build` on. +Use the `--target` flag to compile your standalone executable for a different operating system, architecture, or version of Bun than the machine you're running `bun build` on. To build for Linux x64 (most servers): @@ -94,7 +94,7 @@ To build for Linux x64 (most servers): -To build for Linux ARM64 (e.g. Graviton or Raspberry Pi): +To build for Linux ARM64 (for example, Graviton or Raspberry Pi): @@ -129,7 +129,7 @@ To build for Windows x64: # To explicitly only support CPUs from 2013 and later, use the modern version (haswell) bun build --compile --target=bun-windows-x64-modern ./path/to/my/app.ts --outfile myapp - # note: if no .exe extension is provided, Bun will automatically add it for Windows executables + # note: if no .exe extension is provided, Bun adds it automatically for Windows executables ``` @@ -164,7 +164,7 @@ To build for Windows arm64: ```bash icon="terminal" terminal bun build --compile --target=bun-windows-arm64 ./path/to/my/app.ts --outfile myapp - # note: if no .exe extension is provided, Bun will automatically add it for Windows executables + # note: if no .exe extension is provided, Bun adds it automatically for Windows executables ``` @@ -226,7 +226,7 @@ To build for macOS x64: ### Supported targets -The order of the `--target` flag does not matter, as long as they're delimited by a `-`. +The segments of the `--target` value can appear in any order, as long as they're delimited by `-`. | --target | Operating System | Architecture | Modern | Baseline | Libc | | -------------------- | ---------------- | ------------ | ------ | -------- | ----- | @@ -240,11 +240,10 @@ The order of the `--target` flag does not matter, as long as they're delimited b | bun-linux-arm64-musl | Linux | arm64 | ✅ | N/A | musl | - On x64 platforms, Bun uses SIMD optimizations which require a modern CPU supporting AVX2 instructions. The `-baseline` - build of Bun is for older CPUs that don't support these optimizations. Normally, when you install Bun we automatically - detect which version to use but this can be harder to do when cross-compiling since you might not know the target CPU. - You usually don't need to worry about it on Darwin x64, but it is relevant for Windows x64 and Linux x64. If you or - your users see `"Illegal instruction"` errors, you might need to use the baseline version. + On x64 platforms, Bun uses SIMD optimizations that require a CPU with AVX2 instructions. The `-baseline` build of Bun + is for older CPUs without them. The Bun installer detects which version to use, but when cross-compiling you might not + know the target CPU. This mostly matters on Windows x64 and Linux x64, rarely on Darwin x64. If you or your users see + `"Illegal instruction"` errors, you might need to use the baseline version. --- @@ -275,12 +274,9 @@ Use the `--define` flag to inject build-time constants into your executable, suc -These constants are embedded directly into your compiled binary at build time, providing zero runtime overhead and enabling dead code elimination optimizations. +Bun inlines these constants into the binary at build time, so they cost nothing at runtime and enable dead code elimination. - - For comprehensive examples and advanced patterns, see the [Build-time constants - guide](/guides/runtime/build-time-constants). - +For more examples and patterns, see the [Build-time constants guide](/guides/runtime/build-time-constants). --- @@ -288,9 +284,9 @@ These constants are embedded directly into your compiled binary at build time, p Compiled executables reduce memory usage and improve Bun's start time. -Normally, Bun reads and transpiles JavaScript and TypeScript files on `import` and `require`. This is part of what makes so much of Bun "just work", but it's not free. It costs time and memory to read files from disk, resolve file paths, parse, transpile, and print source code. +Normally, Bun reads and transpiles JavaScript and TypeScript files on `import` and `require`. This is part of what makes so much of Bun "just work", but it's not free: reading files from disk, resolving paths, parsing, transpiling, and printing source code costs time and memory. -With compiled executables, you can move that cost from runtime to build-time. +Compiled executables move that cost from runtime to build time. When deploying to production, we recommend the following: @@ -351,17 +347,17 @@ Bytecode compilation moves parsing overhead for large input files from runtime t ### What do these flags do? -The `--minify` argument optimizes the size of the transpiled output code. If you have a large application, this can save megabytes of space. For smaller applications, it might still improve start time a little. +The `--minify` argument reduces the size of the transpiled output code. For a large application, this can save megabytes of space. For smaller applications, it might still improve start time a little. -The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that errors & stacktraces point to their original locations instead of the transpiled location. Bun will automatically decompress & resolve the sourcemap when an error occurs. +The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that errors & stacktraces point to their original locations instead of the transpiled location. Bun decompresses & resolves the sourcemap automatically when an error occurs. -The `--bytecode` argument enables bytecode compilation. Every time you run JavaScript code in Bun, JavaScriptCore (the engine) will compile your source code into bytecode. We can move this parsing work from runtime to bundle time, saving you startup time. +The `--bytecode` argument enables bytecode compilation. Every time you run JavaScript code in Bun, JavaScriptCore (the engine) compiles your source code into bytecode. `--bytecode` moves that parsing work from runtime to bundle time, which shortens startup. --- ## Embedding runtime arguments -**`--compile-exec-argv="args"`** - Embed runtime arguments that are available via `process.execArgv`: +**`--compile-exec-argv="args"`** - Embed runtime arguments, available at runtime in `process.execArgv`: @@ -389,7 +385,7 @@ console.log(process.execArgv); // ["--smol", "--user-agent=MyBot"] ### Runtime arguments via `BUN_OPTIONS` -The `BUN_OPTIONS` environment variable is applied to standalone executables, allowing you to pass runtime flags without recompiling: +Standalone executables read the `BUN_OPTIONS` environment variable, so you can pass runtime flags without recompiling: ```bash terminal icon="terminal" # Enable CPU profiling on a compiled executable @@ -402,8 +398,6 @@ BUN_OPTIONS="--heap-prof-md" ./myapp BUN_OPTIONS="--smol --cpu-prof-md" ./myapp ``` -This is useful for debugging or profiling production executables without rebuilding them. - --- ## Automatic config loading @@ -419,7 +413,7 @@ Standalone executables can automatically load configuration files from the direc ### Enabling config loading at runtime -If your executable needs to read `tsconfig.json` or `package.json` at runtime, you can opt in with the new CLI flags: +If your executable needs to read `tsconfig.json` or `package.json` at runtime, opt in with these flags: ```bash icon="terminal" terminal # Enable runtime loading of tsconfig.json @@ -476,7 +470,7 @@ To disable `.env` or `bunfig.toml` loading for deterministic execution: New in Bun v1.2.16 -You can run a standalone executable as if it were the `bun` CLI itself by setting the `BUN_BE_BUN=1` environment variable. When this variable is set, the executable will ignore its bundled entrypoint and instead expose all the features of Bun's CLI. +Set the `BUN_BE_BUN=1` environment variable to run a standalone executable as if it were the `bun` CLI itself. The executable ignores its bundled entrypoint and exposes the full `bun` CLI instead. For example, consider an executable compiled from this script: @@ -490,7 +484,7 @@ bun build --compile ./such-bun.js [89ms] compile such-bun ``` -Normally, running `./such-bun` with arguments would execute the script. +Normally, running `./such-bun` with arguments executes the script. ```bash icon="terminal" terminal # Executable runs its own entrypoint by default @@ -501,7 +495,7 @@ Normally, running `./such-bun` with arguments would execute the script. you shouldn't see this ``` -However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary: +However, with the `BUN_BE_BUN=1` environment variable, it acts like the `bun` binary: ```bash icon="terminal" terminal # With the env var, the executable acts like the `bun` CLI @@ -513,7 +507,7 @@ bun install v1.2.16-canary.1 (1d1db811) Checked 63 installs across 64 packages (no changes) [5.00ms] ``` -This is useful for building CLI tools on top of Bun that may need to install packages, bundle dependencies, run different or local files and more without needing to download a separate binary or install bun. +CLI tools built on top of Bun can use this to install packages, bundle dependencies, or run other files without downloading a separate binary or installing Bun. --- @@ -521,7 +515,7 @@ This is useful for building CLI tools on top of Bun that may need to install pac New in Bun v1.2.17 -Bun's `--compile` flag can create standalone executables that contain both server and client code, making it ideal for full-stack applications. When you import an HTML file in your server code, Bun automatically bundles all frontend assets (JavaScript, CSS, etc.) and embeds them into the executable. When Bun sees the HTML import on the server, it kicks off a frontend build process to bundle JavaScript, CSS, and other assets. +The `--compile` flag can create a standalone executable that contains both server and client code, which suits full-stack applications. When you import an HTML file in your server code, Bun bundles the frontend assets (JavaScript, CSS, and so on) and embeds them into the executable. @@ -592,15 +586,15 @@ This creates a self-contained binary that includes: - All frontend assets (HTML, CSS, JavaScript) - Any npm packages used by your server -The result is a single file that can be deployed anywhere without needing Node.js, Bun, or any dependencies installed. Just run: +The result is a single file you can deploy anywhere without installing Node.js, Bun, or any dependencies: ```bash terminal icon="terminal" ./myapp ``` -Bun automatically handles serving the frontend assets with proper MIME types and cache headers. The HTML import is replaced with a manifest object that `Bun.serve` uses to efficiently serve pre-bundled assets. +Bun serves the frontend assets with the correct MIME types and cache headers. The HTML import is replaced with a manifest object that `Bun.serve` uses to serve the pre-bundled assets. -For more details on building full-stack applications with Bun, see the [full-stack guide](/bundler/fullstack). +For more on building full-stack applications, see the [full-stack guide](/bundler/fullstack). --- @@ -637,11 +631,11 @@ new Worker(new URL("./my-worker.ts", import.meta.url)); new Worker(new URL("./my-worker.ts", import.meta.url).href); ``` -When you add multiple entrypoints to a standalone executable, they will be bundled separately into the executable. +When you add multiple entrypoints to a standalone executable, each is bundled separately into the executable. -In the future, we may automatically detect usages of statically-known paths in `new Worker(path)` and then bundle those into the executable, but for now, you'll need to add it to the shell command manually like the above example. +We may eventually detect statically-known paths in `new Worker(path)` and bundle them automatically, but for now you need to list the worker file as an entrypoint, as in the earlier example. -If you use a relative path to a file not included in the standalone executable, it will attempt to load that path from disk relative to the current working directory of the process (and then error if it doesn't exist). +If you use a relative path to a file not included in the standalone executable, Bun loads that path from disk relative to the process's current working directory, and errors if it doesn't exist. --- @@ -657,7 +651,7 @@ import db from "./my.db" with { type: "sqlite" }; console.log(db.query("select * from users LIMIT 1").get()); ``` -That means if the executable is located at `/usr/bin/hello`, the user's terminal is located at `/home/me/Desktop`, it will look for `/home/me/Desktop/my.db`. +That means if the executable is at `/usr/bin/hello` and the user's terminal is in `/home/me/Desktop`, Bun looks for `/home/me/Desktop/my.db`. ```bash terminal icon="terminal" cd /home/me/Desktop @@ -668,7 +662,7 @@ cd /home/me/Desktop ## Embed assets & files -Standalone executables support embedding files directly into the binary. This lets you ship a single executable that contains images, JSON configs, templates, or any other assets your application needs. +Standalone executables can embed files directly into the binary, so a single executable can ship images, JSON configs, templates, or any other assets your application needs. ### How it works @@ -715,7 +709,7 @@ export default { ### Reading embedded files with Node.js fs -Embedded files work seamlessly with Node.js file system APIs: +Embedded files work with the Node.js file system APIs: ```ts index.ts icon="/icons/typescript.svg" import icon from "./icon.png" with { type: "file" }; @@ -807,7 +801,7 @@ const fontData = await file(fontPath).bytes(); ### Embed SQLite databases -If your application wants to embed a SQLite database into the compiled executable, set `type: "sqlite"` in the import attribute and the `embed` attribute to `"true"`. +To embed a SQLite database into the compiled executable, set `type: "sqlite"` in the import attribute and the `embed` attribute to `"true"`. The database file must already exist on disk. Then, import it in your code: @@ -841,7 +835,7 @@ const addon = require("./addon.node"); console.log(addon.hello()); ``` -Unfortunately, if you're using `@mapbox/node-pre-gyp` or other similar tools, you'll need to make sure the `.node` file is directly required or it won't bundle correctly. +If you're using `@mapbox/node-pre-gyp` or similar tools, the `.node` file must be required directly or it won't bundle correctly. ### Embed directories @@ -886,7 +880,7 @@ export default { }; ``` -This is honestly a workaround, and we expect to improve this in the future with a more direct API. +This is a workaround, and we expect to replace it with a more direct API. ### Detecting standalone mode at runtime @@ -904,7 +898,7 @@ Unlike `Bun.embeddedFiles.length > 0`, this check does not allocate `Blob` objec ### Listing embedded files -`Bun.embeddedFiles` gives you access to all embedded files as `Blob` objects: +`Bun.embeddedFiles` exposes all embedded files as `Blob` objects: ```ts index.ts icon="/icons/typescript.svg" import "./icon.png" with { type: "file" }; @@ -928,7 +922,7 @@ Each item in `Bun.embeddedFiles` is a `Blob` with a `name` property: embeddedFiles: ReadonlyArray; ``` -This is useful for dynamically serving all embedded assets using `static` routes: +Use it to serve every embedded asset through `static` routes: ```ts server.ts icon="/icons/typescript.svg" import "./public/favicon.ico" with { type: "file" }; @@ -958,9 +952,7 @@ serve({ #### Content hash -By default, embedded files have a content hash appended to their name. This is useful for situations where you want to serve the file from a URL or CDN and have fewer cache invalidation issues. But sometimes, this is unexpected and you might want the original name instead: - -To disable the content hash, configure asset naming: +By default, embedded files have a content hash appended to their name, which helps with cache invalidation when you serve them from a URL or CDN. To keep the original name instead, configure asset naming: @@ -1028,7 +1020,7 @@ This uses Bun's minifier to reduce the code size. Overall though, Bun's binary i ## Windows-specific flags -When compiling a standalone executable on Windows, there are platform-specific options to customize metadata on the generated `.exe` file: +When compiling a standalone executable on Windows, platform-specific options customize metadata on the generated `.exe` file: @@ -1073,7 +1065,7 @@ Available Windows options: - `description` - Description in file properties - `copyright` - Copyright notice in file properties -These flags currently cannot be used when cross-compiling because they depend on Windows APIs. +These flags cannot be used when cross-compiling because they depend on Windows APIs. --- @@ -1175,7 +1167,7 @@ Lazy module loaded ## Using plugins -Plugins work with standalone executables, allowing you to transform files during the build process: +Plugins work with standalone executables; use them to transform files during the build: ```ts build.ts icon="/icons/typescript.svg" import type { BunPlugin } from "bun"; @@ -1213,19 +1205,19 @@ console.log(`Running in ${config.environment} mode`); console.log(`API endpoint: ${config.apiUrl}`); ``` -Plugins can perform any transformation: compile YAML/TOML configs, inline SQL queries, generate type-safe API clients, or preprocess templates. Refer to the [plugin documentation](/bundler/plugins) for more details. +Plugins can perform any transformation: compile YAML/TOML configs, inline SQL queries, generate type-safe API clients, or preprocess templates. See the [plugin documentation](/bundler/plugins). --- ## Unsupported CLI arguments -Currently, the `--compile` flag can only accept a single entrypoint at a time and does not support the following flags: +The `--compile` flag can only accept a single entrypoint at a time and does not support the following flags: - `--outdir` — use `outfile` instead (except when using with `--splitting`). - `--public-path` - `--target=node` - `--target=browser` (without HTML entrypoints — see [Standalone HTML](/bundler/standalone-html) for `--compile --target=browser` with `.html` files) -- `--no-bundle` - we always bundle everything into the executable. +- `--no-bundle` - Bun always bundles everything into the executable. --- diff --git a/docs/bundler/fullstack.mdx b/docs/bundler/fullstack.mdx index d77715cc961e..d6bc59b541f9 100644 --- a/docs/bundler/fullstack.mdx +++ b/docs/bundler/fullstack.mdx @@ -57,8 +57,6 @@ bun run app.ts ### HTML Imports as Routes -The web starts with HTML, and so does Bun's fullstack dev server. - To specify entrypoints to your frontend, import HTML files into your JavaScript/TypeScript/TSX/JSX files. ```ts title="app.ts" icon="/icons/typescript.svg" @@ -66,7 +64,7 @@ import dashboard from "./dashboard.html"; import homepage from "./index.html"; ``` -These HTML files are used as routes in Bun's dev server you can pass to `Bun.serve()`. +Pass the imported HTML files as routes to `Bun.serve()`. ```ts title="app.ts" icon="/icons/typescript.svg" Bun.serve({ @@ -204,19 +202,17 @@ Bun.serve({ ### Development Mode Features -When `development` is `true`, Bun will: +When `development` is `true`, Bun: -- Include the SourceMap header in the response so that devtools can show the original source code -- Disable minification -- Re-bundle assets on each request to a `.html` file -- Enable hot module reloading (unless `hmr: false` is set) -- Echo console logs from browser to terminal +- Includes the SourceMap header in the response so that devtools can show the original source code +- Disables minification +- Re-bundles assets on each request to a `.html` file +- Enables hot module reloading (unless `hmr: false` is set) +- Echoes console logs from the browser to the terminal ### Advanced Development Configuration -`Bun.serve()` supports echoing console logs from the browser to the terminal. - -To enable this, pass `console: true` in the development object in `Bun.serve()`. +To echo console logs from the browser to the terminal, pass `console: true` in the `development` object in `Bun.serve()`. ```ts title="src/backend.ts" icon="/icons/typescript.svg" import homepage from "./index.html"; @@ -237,7 +233,7 @@ Bun.serve({ }); ``` -When `console: true` is set, Bun will stream console logs from the browser to the terminal. This reuses the existing WebSocket connection from HMR to send the logs. +Bun sends the logs over the existing HMR WebSocket connection. ### Development vs Production @@ -252,17 +248,17 @@ When `console: true` is set, Bun will stream console logs from the browser to th ## Production Mode -Hot reloading and `development: true` helps you iterate quickly, but in production, your server should be as fast as possible and have as few external dependencies as possible. +Hot reloading and `development: true` help you iterate quickly, but in production your server should be as fast as possible and have as few external dependencies as possible. ### Ahead of Time Bundling (Recommended) -As of Bun v1.2.17, you can use `Bun.build` or `bun build` to bundle your full-stack application ahead of time. +As of Bun v1.2.17, you can use `Bun.build` or `bun build` to bundle your fullstack application ahead of time. ```bash terminal icon="terminal" bun build --target=bun --production --outdir=dist ./src/index.ts ``` -When Bun's bundler sees an HTML import from server-side code, it will bundle the referenced JavaScript/TypeScript/TSX/JSX and CSS files into a manifest object that `Bun.serve()` can use to serve the assets. +When Bun's bundler sees an HTML import from server-side code, it bundles the referenced JavaScript/TypeScript/TSX/JSX and CSS files into a manifest object that `Bun.serve()` can use to serve the assets. ```ts title="src/backend.ts" icon="/icons/typescript.svg" import { serve } from "bun"; @@ -275,13 +271,13 @@ serve({ ### Runtime Bundling -When adding a build step is too complicated, you can set `development: false` in `Bun.serve()`. +If you'd rather not add a build step, set `development: false` in `Bun.serve()`. -This will: +This: -- Enable in-memory caching of bundled assets. Bun will bundle assets lazily on the first request to an `.html` file, and cache the result in memory until the server restarts. -- Enable `Cache-Control` headers and `ETag` headers -- Minify JavaScript/TypeScript/TSX/JSX files +- Enables in-memory caching of bundled assets. Bun bundles assets lazily on the first request to an `.html` file and caches the result in memory until the server restarts. +- Enables `Cache-Control` and `ETag` headers +- Minifies JavaScript/TypeScript/TSX/JSX files ```ts title="src/backend.ts" icon="/icons/typescript.svg" import { serve } from "bun"; @@ -410,7 +406,7 @@ To configure plugins for `Bun.serve`, add a `plugins` array in the `[serve.stati ### TailwindCSS Plugin -You can use TailwindCSS by installing and adding the `tailwindcss` package and `bun-plugin-tailwind` plugin. +To use TailwindCSS, install the `tailwindcss` package and the `bun-plugin-tailwind` plugin. ```bash terminal icon="terminal" bun add tailwindcss bun-plugin-tailwind @@ -421,7 +417,7 @@ bun add tailwindcss bun-plugin-tailwind plugins = ["bun-plugin-tailwind"] ``` -This will allow you to use TailwindCSS utility classes in your HTML and CSS files. Import `tailwindcss` somewhere in your project: +You can now use TailwindCSS utility classes in your HTML and CSS files. Import `tailwindcss` somewhere in your project: ```html title="index.html" icon="file-code" @@ -457,7 +453,7 @@ Alternatively, you can import TailwindCSS in your CSS file: ### Custom Plugins -Any JS file or module which exports a valid bundler plugin object (essentially an object with a `name` and `setup` field) can be placed inside the plugins array: +Any JS file or module that exports a valid bundler plugin object (an object with a `name` and a `setup` field) can be placed in the plugins array: ```toml title="bunfig.toml" icon="settings" [serve.static] @@ -484,17 +480,16 @@ const myPlugin: BunPlugin = { export default myPlugin; ``` -Bun will lazily resolve and load each plugin and use them to bundle your routes. +Bun lazily resolves and loads each plugin and uses them to bundle your routes. - This is currently in `bunfig.toml` to make it possible to know statically which plugins are in use when we eventually - integrate this with the `bun build` CLI. These plugins work in `Bun.build()`'s JS API, but are not yet supported in - the CLI. + Plugins live in `bunfig.toml` so that the `bun build` CLI, once it supports them, can know statically which plugins + are in use. These plugins work in `Bun.build()`'s JS API, but not yet in the CLI. ## Inline Environment Variables -Bun can replace `process.env.*` references in your frontend JavaScript and TypeScript with their actual values at build time. Configure the `env` option in your `bunfig.toml`: +Bun can replace `process.env.*` references in your frontend JavaScript and TypeScript with their values at build time. Configure the `env` option in your `bunfig.toml`: ```toml title="bunfig.toml" icon="settings" [serve.static] @@ -512,7 +507,7 @@ If an environment variable is not set, you may see runtime errors like `Referenc -See the [HTML & static sites documentation](/bundler/html-static#inline-environment-variables) for more details on build-time configuration and examples. +See [HTML & static sites](/bundler/html-static#inline-environment-variables) for build-time configuration and examples. ## How It Works @@ -559,8 +554,6 @@ Bun uses `HTMLRewriter` to scan for `"); @@ -21,4 +21,4 @@ Bun.escapeHTML(""); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/file-url-to-path.mdx b/docs/guides/util/file-url-to-path.mdx index 3990f3befb58..1dd873c2dc65 100644 --- a/docs/guides/util/file-url-to-path.mdx +++ b/docs/guides/util/file-url-to-path.mdx @@ -13,4 +13,4 @@ Bun.fileURLToPath("file:///path/to/file.txt"); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/gzip.mdx b/docs/guides/util/gzip.mdx index 0a3763f9ed73..ed398eaf1641 100644 --- a/docs/guides/util/gzip.mdx +++ b/docs/guides/util/gzip.mdx @@ -17,4 +17,4 @@ const decompressed = Bun.gunzipSync(compressed); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/hash-a-password.mdx b/docs/guides/util/hash-a-password.mdx index 13d0d69c4400..ebdb75ebea9a 100644 --- a/docs/guides/util/hash-a-password.mdx +++ b/docs/guides/util/hash-a-password.mdx @@ -4,7 +4,7 @@ sidebarTitle: Hash password mode: center --- -The `Bun.password.hash()` function provides a fast, built-in mechanism for securely hashing passwords in Bun. No third-party dependencies are required. +Use `Bun.password.hash()` to securely hash passwords. It's built into Bun, with no third-party dependencies. ```ts const password = "super-secure-pa$$word"; @@ -15,7 +15,7 @@ const hash = await Bun.password.hash(password); --- -By default, this uses the [Argon2id](https://en.wikipedia.org/wiki/Argon2) algorithm. Pass a second argument to `Bun.password.hash()` to use a different algorithm or configure the hashing parameters. +By default, `Bun.password.hash()` uses the [Argon2id](https://en.wikipedia.org/wiki/Argon2) algorithm. Pass a second argument to use a different algorithm or configure the hashing parameters. ```ts const password = "super-secure-pa$$word"; @@ -42,7 +42,7 @@ const bcryptHash = await Bun.password.hash(password, { --- -Use `Bun.password.verify()` to verify a password. The algorithm and its parameters are stored in the hash itself, so re-specifying configuration is unnecessary. +Use `Bun.password.verify()` to verify a password. The hash stores the algorithm and its parameters, so you don't need to specify them again. ```ts const password = "super-secure-pa$$word"; @@ -54,4 +54,4 @@ const isMatch = await Bun.password.verify(password, hash); --- -See [Docs > API > Hashing](/runtime/hashing#bun-password) for complete documentation. +See [`Bun.password`](/runtime/hashing#bun-password). diff --git a/docs/guides/util/import-meta-dir.mdx b/docs/guides/util/import-meta-dir.mdx index 8a2355cd8928..6cf53c1f3555 100644 --- a/docs/guides/util/import-meta-dir.mdx +++ b/docs/guides/util/import-meta-dir.mdx @@ -4,7 +4,7 @@ sidebarTitle: import.meta.dir mode: center --- -Bun provides a handful of module-specific utilities on the [`import.meta`](/runtime/module-resolution#import-meta) object. +Bun provides a handful of module-specific utilities on the [`import.meta`](/runtime/module-resolution#import-meta) object. Use `import.meta.dir` to retrieve the absolute path to the directory containing the current file. ```ts /a/b/c.ts icon="/icons/typescript.svg" import.meta.dir; // => "/a/b" @@ -12,4 +12,4 @@ import.meta.dir; // => "/a/b" --- -See [Docs > API > import.meta](/runtime/module-resolution#import-meta) for complete documentation. +See [`import.meta`](/runtime/module-resolution#import-meta). diff --git a/docs/guides/util/import-meta-file.mdx b/docs/guides/util/import-meta-file.mdx index 01edbafa66cd..11429a649ed2 100644 --- a/docs/guides/util/import-meta-file.mdx +++ b/docs/guides/util/import-meta-file.mdx @@ -12,4 +12,4 @@ import.meta.file; // => "c.ts" --- -See [Docs > API > import.meta](/runtime/module-resolution#import-meta) for complete documentation. +See [`import.meta`](/runtime/module-resolution#import-meta). diff --git a/docs/guides/util/import-meta-path.mdx b/docs/guides/util/import-meta-path.mdx index 80e92bfd1f9d..969d500e7fac 100644 --- a/docs/guides/util/import-meta-path.mdx +++ b/docs/guides/util/import-meta-path.mdx @@ -12,4 +12,4 @@ import.meta.path; // => "/a/b/c.ts" --- -See [Docs > API > import.meta](/runtime/module-resolution#import-meta) for complete documentation. +See [`import.meta`](/runtime/module-resolution#import-meta). diff --git a/docs/guides/util/javascript-uuid.mdx b/docs/guides/util/javascript-uuid.mdx index 1c0d4bfa6be2..9ea991625e44 100644 --- a/docs/guides/util/javascript-uuid.mdx +++ b/docs/guides/util/javascript-uuid.mdx @@ -4,7 +4,7 @@ sidebarTitle: Generate UUID mode: center --- -Use `crypto.randomUUID()` to generate a UUID v4. This API works in Bun, Node.js, and browsers. It requires no dependencies. +Use `crypto.randomUUID()` to generate a UUID v4. It works in Bun, Node.js, and browsers, with no dependencies. ```ts crypto.randomUUID(); @@ -13,7 +13,7 @@ crypto.randomUUID(); --- -In Bun, you can also use `Bun.randomUUIDv7()` to generate a [UUID v7](https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-01.html). +Bun also provides `Bun.randomUUIDv7()`, which generates a [UUID v7](https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-01.html). ```ts Bun.randomUUIDv7(); @@ -22,4 +22,4 @@ Bun.randomUUIDv7(); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/main.mdx b/docs/guides/util/main.mdx index ea41dbf2d153..1b8068febda0 100644 --- a/docs/guides/util/main.mdx +++ b/docs/guides/util/main.mdx @@ -20,7 +20,7 @@ import "./foo.ts"; --- -The printed path corresponds to the file that is executed with `bun run`. +The printed path is the file executed with `bun run`. ```sh terminal icon="terminal" bun run index.ts @@ -40,4 +40,4 @@ bun run foo.ts --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/path-to-file-url.mdx b/docs/guides/util/path-to-file-url.mdx index 65ffe7b201e0..b87934354ed2 100644 --- a/docs/guides/util/path-to-file-url.mdx +++ b/docs/guides/util/path-to-file-url.mdx @@ -13,4 +13,4 @@ Bun.pathToFileURL("/path/to/file.txt"); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/sleep.mdx b/docs/guides/util/sleep.mdx index 738738c2137e..430d33b24a9c 100644 --- a/docs/guides/util/sleep.mdx +++ b/docs/guides/util/sleep.mdx @@ -4,7 +4,7 @@ sidebarTitle: Sleep mode: center --- -The `Bun.sleep` method provides a convenient way to create a void `Promise` that resolves in a fixed number of milliseconds. +`Bun.sleep()` returns a void `Promise` that resolves after a given number of milliseconds. ```ts // sleep for 1 second @@ -13,7 +13,7 @@ await Bun.sleep(1000); --- -Internally, this is equivalent to the following snippet that uses [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). +Internally, it is equivalent to the following [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) snippet. ```ts await new Promise(resolve => setTimeout(resolve, ms)); @@ -21,4 +21,4 @@ await new Promise(resolve => setTimeout(resolve, ms)); --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/upgrade.mdx b/docs/guides/util/upgrade.mdx index dea2faacd1b3..327315382e7a 100644 --- a/docs/guides/util/upgrade.mdx +++ b/docs/guides/util/upgrade.mdx @@ -4,13 +4,13 @@ sidebarTitle: Upgrade Bun mode: center --- -Bun can upgrade itself using the built-in `bun upgrade` command. This is the fastest way to get the latest features and bug fixes. +Bun upgrades itself with the built-in `bun upgrade` command. ```bash terminal icon="terminal" bun upgrade ``` -This downloads and installs the latest stable version of Bun, replacing the currently installed version. +`bun upgrade` downloads and installs the latest stable version of Bun, replacing the currently installed version. To see the current version of Bun, run `bun --version`. @@ -33,7 +33,7 @@ bun --revision ## Upgrade to canary builds -Canary builds are automatically released on every commit to the `main` branch. These are untested but useful for trying new features or verifying bug fixes before they're released. +Canary builds are released on every commit to the `main` branch. They're untested, but useful for trying new features or verifying bug fixes before a release. ```bash terminal icon="terminal" bun upgrade --canary @@ -74,14 +74,14 @@ To install a specific version of Bun, use the install script with a version tag: ## Package manager users -If you installed Bun via a package manager, use that package manager to upgrade instead of `bun upgrade` to avoid conflicts. +If you installed Bun with a package manager, upgrade with that package manager instead of `bun upgrade` to avoid conflicts. **Homebrew users**
-To avoid conflicts with Homebrew, use `brew upgrade bun` instead. +Use `brew upgrade bun` instead. **Scoop users**
-To avoid conflicts with Scoop, use `scoop update bun` instead. +Use `scoop update bun` instead.
diff --git a/docs/guides/util/version.mdx b/docs/guides/util/version.mdx index 6348fbf9e59c..d933b46a15b6 100644 --- a/docs/guides/util/version.mdx +++ b/docs/guides/util/version.mdx @@ -4,7 +4,7 @@ sidebarTitle: Get Bun version mode: center --- -Get the current version of Bun in a semver format. +`Bun.version` contains the current version of Bun in semver format. ```ts index.ts icon="/icons/typescript.svg" Bun.version; // => "1.3.3" @@ -12,7 +12,7 @@ Bun.version; // => "1.3.3" --- -Get the exact `git` commit of [`oven-sh/bun`](https://github.com/oven-sh/bun) that was compiled to produce this Bun binary. +`Bun.revision` contains the exact `git` commit of [`oven-sh/bun`](https://github.com/oven-sh/bun) that was compiled to produce this Bun binary. ```ts index.ts icon="/icons/typescript.svg" Bun.revision; // => "49231b2cb9aa48497ab966fc0bb6b742dacc4994" @@ -20,4 +20,4 @@ Bun.revision; // => "49231b2cb9aa48497ab966fc0bb6b742dacc4994" --- -See [Docs > API > Utils](/runtime/utils) for more useful utilities. +See [Utils](/runtime/utils). diff --git a/docs/guides/util/which-path-to-executable-bin.mdx b/docs/guides/util/which-path-to-executable-bin.mdx index e52456108997..8e0d036f5b89 100644 --- a/docs/guides/util/which-path-to-executable-bin.mdx +++ b/docs/guides/util/which-path-to-executable-bin.mdx @@ -4,7 +4,7 @@ sidebarTitle: Find executable path mode: center --- -`Bun.which` is a utility function to find the absolute path of an executable file. It is similar to the `which` command in Unix-like systems. +`Bun.which` finds the absolute path of an executable file, like the `which` command on Unix-like systems. ```ts foo.ts icon="/icons/typescript.svg" Bun.which("sh"); // => "/bin/sh" @@ -14,4 +14,4 @@ Bun.which("bun"); // => "/home/user/.bun/bin/bun" --- -See [Docs > API > Utils](/runtime/utils#bun-which) for complete documentation. +See [`Bun.which`](/runtime/utils#bun-which). diff --git a/docs/guides/websocket/compression.mdx b/docs/guides/websocket/compression.mdx index ef1075b80e5b..e4556e51ffa6 100644 --- a/docs/guides/websocket/compression.mdx +++ b/docs/guides/websocket/compression.mdx @@ -4,7 +4,7 @@ sidebarTitle: Enable compression mode: center --- -Per-message compression can be enabled with the `perMessageDeflate` parameter. When set, all messages will be compressed using the [permessage-deflate](https://tools.ietf.org/html/rfc7692) WebSocket extension. +Set the `perMessageDeflate` parameter to compress all messages with the [permessage-deflate](https://tools.ietf.org/html/rfc7692) WebSocket extension. ```ts server.ts icon="/icons/typescript.svg" Bun.serve({ diff --git a/docs/guides/websocket/context.mdx b/docs/guides/websocket/context.mdx index 3104ec9a12d4..50807344bbea 100644 --- a/docs/guides/websocket/context.mdx +++ b/docs/guides/websocket/context.mdx @@ -4,9 +4,9 @@ sidebarTitle: Contextual data mode: center --- -When building a WebSocket server, it's typically necessary to store some identifying information or context associated with each connected client. +A WebSocket server typically needs to store some identifying information or context for each connected client. -With [Bun.serve()](/runtime/http/websockets#contextual-data), this "contextual data" is set when the connection is initially upgraded by passing a `data` parameter in the `server.upgrade()` call. +With [Bun.serve()](/runtime/http/websockets#contextual-data), set this "contextual data" by passing a `data` parameter to `server.upgrade()` when upgrading the connection. ```ts server.ts icon="/icons/typescript.svg" Bun.serve({ diff --git a/docs/guides/websocket/pubsub.mdx b/docs/guides/websocket/pubsub.mdx index 17fe47fba48d..6ffe5de15aca 100644 --- a/docs/guides/websocket/pubsub.mdx +++ b/docs/guides/websocket/pubsub.mdx @@ -4,7 +4,7 @@ sidebarTitle: Pub-sub server mode: center --- -Bun's server-side `WebSocket` API provides a native pub-sub API. Sockets can be subscribed to a set of named channels using `socket.subscribe()`; messages can be published to a channel using `socket.publish(, )`. +Bun's server-side `WebSocket` API includes native pub-sub. Subscribe a socket to a set of named channels with `socket.subscribe()`; publish a message to a channel with `socket.publish(, )`. This code snippet implements a single-channel chat server. diff --git a/docs/guides/websocket/simple.mdx b/docs/guides/websocket/simple.mdx index 6239d13365b2..31d83de5dfcf 100644 --- a/docs/guides/websocket/simple.mdx +++ b/docs/guides/websocket/simple.mdx @@ -4,9 +4,9 @@ sidebarTitle: Simple server mode: center --- -Start a simple WebSocket server using [`Bun.serve`](/runtime/http/server). +Start a WebSocket server with [`Bun.serve`](/runtime/http/server). -Inside `fetch`, we attempt to upgrade incoming `ws:` or `wss:` requests to WebSocket connections. +Inside `fetch`, `server.upgrade()` attempts to upgrade incoming `ws:` or `wss:` requests to WebSocket connections. ```ts server.ts icon="/icons/typescript.svg" const server = Bun.serve({ diff --git a/docs/guides/write-file/append.mdx b/docs/guides/write-file/append.mdx index 44104e107689..82685dcc5240 100644 --- a/docs/guides/write-file/append.mdx +++ b/docs/guides/write-file/append.mdx @@ -8,7 +8,7 @@ Bun implements the `node:fs` module, which includes the `fs.appendFile` and `fs. --- -You can use `fs.appendFile` to asynchronously append data to a file, creating the file if it does not yet exist. The content can be a string or a `Buffer`. +`fs.appendFile` asynchronously appends data to a file, creating the file if it does not yet exist. The content can be a string or a `Buffer`. ```ts import { appendFile } from "node:fs/promises"; @@ -51,4 +51,4 @@ appendFileSync("message.txt", "data to append", "utf8"); --- -See the [Node.js documentation](https://nodejs.org/api/fs.html#fspromisesappendfilepath-data-options) for more information. +See the [Node.js documentation](https://nodejs.org/api/fs.html#fspromisesappendfilepath-data-options) for `fs.appendFile`. diff --git a/docs/guides/write-file/basic.mdx b/docs/guides/write-file/basic.mdx index 6f3eec528773..7581a7586feb 100644 --- a/docs/guides/write-file/basic.mdx +++ b/docs/guides/write-file/basic.mdx @@ -4,9 +4,7 @@ sidebarTitle: Write string to file mode: center --- -This code snippet writes a string to disk at a particular _absolute path_. - -It uses the fast [`Bun.write()`](/runtime/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_; the second is the _data_ to write. +Use [`Bun.write()`](/runtime/file-io#writing-files-bun-write) to write a string to disk at an _absolute path_. The first argument is a _destination_; the second is the _data_ to write. ```ts const path = "/path/to/file.txt"; @@ -15,7 +13,7 @@ await Bun.write(path, "Lorem ipsum"); --- -Any relative paths will be resolved relative to the project root (the nearest directory containing a `package.json` file). +Bun resolves relative paths from the project root (the nearest directory containing a `package.json` file). ```ts const path = "./file.txt"; @@ -24,7 +22,7 @@ await Bun.write(path, "Lorem ipsum"); --- -You can pass a `BunFile` as the destination. `Bun.write()` will write the data to its associated path. +You can pass a `BunFile` as the destination. `Bun.write()` writes the data to its associated path. ```ts const path = Bun.file("./file.txt"); @@ -43,4 +41,4 @@ const bytes = await Bun.write(path, "Lorem ipsum"); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/blob.mdx b/docs/guides/write-file/blob.mdx index 78810b740d40..0f2fdddc2b7b 100644 --- a/docs/guides/write-file/blob.mdx +++ b/docs/guides/write-file/blob.mdx @@ -4,9 +4,7 @@ sidebarTitle: Write Blob mode: center --- -This code snippet writes a `Blob` to disk at a particular path. - -It uses the fast [`Bun.write()`](/runtime/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. +Use [`Bun.write()`](/runtime/file-io#writing-files-bun-write) to write a `Blob` to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. ```ts const path = "/path/to/file.txt"; @@ -27,4 +25,4 @@ await Bun.write(path, data); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/cat.mdx b/docs/guides/write-file/cat.mdx index 92ca362e0462..dda952de7cb3 100644 --- a/docs/guides/write-file/cat.mdx +++ b/docs/guides/write-file/cat.mdx @@ -4,9 +4,9 @@ sidebarTitle: Write file to stdout mode: center --- -Bun exposes `stdout` as a `BunFile` with the `Bun.stdout` property. This can be used as a destination for [`Bun.write()`](/runtime/file-io#writing-files-bun-write). +Bun exposes `stdout` as a `BunFile` with the `Bun.stdout` property. Pass it as the destination to [`Bun.write()`](/runtime/file-io#writing-files-bun-write). -This code writes a file to `stdout` similar to the `cat` command in Unix. +The following code writes a file to `stdout`, like the Unix `cat` command. ```ts cat.ts icon="/icons/typescript.svg" const path = "/path/to/file.txt"; @@ -16,4 +16,4 @@ await Bun.write(Bun.stdout, file); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/file-cp.mdx b/docs/guides/write-file/file-cp.mdx index d8eb08d67c92..b5d268ef3747 100644 --- a/docs/guides/write-file/file-cp.mdx +++ b/docs/guides/write-file/file-cp.mdx @@ -4,9 +4,7 @@ sidebarTitle: Copy file mode: center --- -This code snippet copies a file to another location on disk. - -It uses the fast [`Bun.write()`](/runtime/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. +Use [`Bun.write()`](/runtime/file-io#writing-files-bun-write) to copy a file to another location on disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. ```ts const file = Bun.file("/path/to/original.txt"); @@ -15,4 +13,4 @@ await Bun.write("/path/to/copy.txt", file); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/filesink.mdx b/docs/guides/write-file/filesink.mdx index 68333e544517..1278c7ae2a76 100644 --- a/docs/guides/write-file/filesink.mdx +++ b/docs/guides/write-file/filesink.mdx @@ -4,9 +4,9 @@ sidebarTitle: Incremental write mode: center --- -Bun provides an API for incrementally writing to a file. This is useful for writing large files, or for writing to a file over a long period of time. +Bun provides an API for incrementally writing to a file. Use it for large files, or when writing to a file over a long period of time. -Call `.writer()` on a `BunFile` to retrieve a `FileSink` instance. This instance can be used to efficiently buffer data and periodically "flush" it to disk. You can write & flush many times. +Call `.writer()` on a `BunFile` to retrieve a `FileSink` instance. It buffers data; call `.flush()` to write the buffer to disk. You can write & flush many times. ```ts const file = Bun.file("/path/to/file.txt"); @@ -23,7 +23,7 @@ writer.flush(); --- -The `.write()` method can accept strings or binary data. +The `.write()` method accepts strings or binary data. ```ts w.write("hello"); @@ -34,7 +34,7 @@ writer.flush(); --- -The `FileSink` will also auto-flush when its internal buffer is full. You can configure the buffer size with the `highWaterMark` option. +The `FileSink` also auto-flushes when its internal buffer is full. You can configure the buffer size with the `highWaterMark` option. ```ts const file = Bun.file("/path/to/file.txt"); @@ -43,7 +43,7 @@ const writer = file.writer({ highWaterMark: 1024 * 1024 }); // 1MB --- -When you're done writing to the file, call `.end()` to auto-flush the buffer and close the file. +When you're done writing, call `.end()` to flush the buffer and close the file. ```ts writer.end(); diff --git a/docs/guides/write-file/response.mdx b/docs/guides/write-file/response.mdx index 20e04ff69c5a..6895fa11c8bd 100644 --- a/docs/guides/write-file/response.mdx +++ b/docs/guides/write-file/response.mdx @@ -4,9 +4,9 @@ sidebarTitle: Write Response mode: center --- -This code snippet writes a `Response` to disk at a particular path. Bun will consume the `Response` body according to its `Content-Type` header. +Use [`Bun.write()`](/runtime/file-io#writing-files-bun-write) to write a `Response` to disk. Bun consumes the `Response` body according to its `Content-Type` header. -It uses the fast [`Bun.write()`](/runtime/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. +The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. ```ts const result = await fetch("https://bun.com"); @@ -16,4 +16,4 @@ await Bun.write(path, result); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/stdout.mdx b/docs/guides/write-file/stdout.mdx index 3c1d9fd6813f..64937c9188c5 100644 --- a/docs/guides/write-file/stdout.mdx +++ b/docs/guides/write-file/stdout.mdx @@ -4,7 +4,7 @@ sidebarTitle: Write to stdout mode: center --- -The `console.log` function writes to `stdout`. It will automatically append a line break at the end of the printed data. +The `console.log` function writes to `stdout` and appends a line break to the printed data. ```ts console.log("Lorem ipsum"); @@ -12,7 +12,7 @@ console.log("Lorem ipsum"); --- -For more advanced use cases, Bun exposes `stdout` as a `BunFile` via the `Bun.stdout` property. This can be used as a destination for [`Bun.write()`](/runtime/file-io#writing-files-bun-write). +Bun also exposes `stdout` as a `BunFile` with the `Bun.stdout` property. Pass it as the destination to [`Bun.write()`](/runtime/file-io#writing-files-bun-write). ```ts await Bun.write(Bun.stdout, "Lorem ipsum"); @@ -20,4 +20,4 @@ await Bun.write(Bun.stdout, "Lorem ipsum"); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/stream.mdx b/docs/guides/write-file/stream.mdx index 1c13bd5c486c..c1a9da459d6a 100644 --- a/docs/guides/write-file/stream.mdx +++ b/docs/guides/write-file/stream.mdx @@ -4,7 +4,7 @@ sidebarTitle: Write stream mode: center --- -To write a `ReadableStream` to disk, first create a `Response` instance from the stream. This `Response` can then be written to disk using [`Bun.write()`](/runtime/file-io#writing-files-bun-write). +To write a `ReadableStream` to disk, create a `Response` from the stream and pass it to [`Bun.write()`](/runtime/file-io#writing-files-bun-write). ```ts const stream: ReadableStream = ...; @@ -16,4 +16,4 @@ await Bun.write(path, response); --- -See [Docs > API > File I/O](/runtime/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. +See [`Bun.write()`](/runtime/file-io#writing-files-bun-write). diff --git a/docs/guides/write-file/unlink.mdx b/docs/guides/write-file/unlink.mdx index 7835f503d212..4b9c41036b9c 100644 --- a/docs/guides/write-file/unlink.mdx +++ b/docs/guides/write-file/unlink.mdx @@ -15,4 +15,4 @@ await file.delete(); --- -See [Docs > API > File I/O](/runtime/file-io#reading-files-bun-file) for complete documentation of `Bun.file()`. +See [`Bun.file()`](/runtime/file-io#reading-files-bun-file). diff --git a/docs/index.mdx b/docs/index.mdx index f3e027413b93..705eb549a929 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -87,13 +87,13 @@ Explore each area using the cards above. Each section is structured with an over Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a single executable called `bun`. -At its core is the _Bun runtime_, a fast JavaScript runtime designed as **a drop-in replacement for Node.js**. It's written in Rust and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage. +At its core is the _Bun runtime_, a fast JavaScript runtime designed as **a drop-in replacement for Node.js**. It's written in Rust and powered by JavaScriptCore, reducing startup time and memory usage. ```bash terminal icon="terminal" -bun run index.tsx # TS and JSX supported out of the box +bun run index.tsx # TS and JSX supported by default ``` -The `bun` command-line tool also implements a test runner, script runner, and Node.js-compatible package manager, all significantly faster than existing tools and usable in existing Node.js projects with little to no changes necessary. +The `bun` command-line tool also implements a test runner, script runner, and Node.js-compatible package manager, all significantly faster than existing tools and usable in existing Node.js projects with little to no changes. ```bash terminal icon="terminal" bun run start # run the `start` script @@ -108,15 +108,15 @@ bunx cowsay 'Hello, world!' # execute a package JavaScript (or, more formally, ECMAScript) is just a _specification_ for a programming language. Anyone can write a JavaScript _engine_ that ingests a valid JavaScript program and executes it. The two most popular engines in use today are V8 (developed by Google) and JavaScriptCore (developed by Apple). Both are open source. -But most JavaScript programs don't run in a vacuum. They need a way to access the outside world to perform useful tasks. This is where _runtimes_ come in. They implement additional APIs that are then made available to the JavaScript programs they execute. +But most JavaScript programs don't run in a vacuum. They need a way to access the outside world to perform useful tasks. This is where _runtimes_ come in. They implement additional APIs and make them available to the JavaScript programs they execute. ### Browsers -Notably, browsers ship with JavaScript runtimes that implement a set of Web-specific APIs that are exposed via the global `window` object. Any JavaScript code executed by the browser can use these APIs to implement interactive or dynamic behavior in the context of the current webpage. +Browsers ship with JavaScript runtimes that implement a set of Web-specific APIs, exposed on the global `window` object. Any JavaScript code executed by the browser can use these APIs to add interactive or dynamic behavior to the current webpage. ### Node.js -Similarly, Node.js is a JavaScript runtime that can be used in non-browser environments, like servers. JavaScript programs executed by Node.js have access to a set of Node.js-specific [globals](https://nodejs.org/api/globals.html) like `Buffer`, `process`, and `__dirname` in addition to built-in modules for performing OS-level tasks like reading/writing files (`node:fs`) and networking (`node:net`, `node:http`). Node.js also implements a CommonJS-based module system and resolution algorithm that pre-dates JavaScript's native module system. +Node.js is a JavaScript runtime for non-browser environments, like servers. JavaScript programs executed by Node.js have access to a set of Node.js-specific [globals](https://nodejs.org/api/globals.html) like `Buffer`, `process`, and `__dirname` in addition to built-in modules for OS-level tasks like reading/writing files (`node:fs`) and networking (`node:net`, `node:http`). Node.js also implements a CommonJS-based module system and resolution algorithm that pre-dates JavaScript's native module system. Bun is designed as a faster, leaner, more modern replacement for Node.js. @@ -124,10 +124,10 @@ Bun is designed as a faster, leaner, more modern replacement for Node.js. Bun is designed from the ground-up with today's JavaScript ecosystem in mind. -- **Speed**. Bun processes start [4x faster than Node.js](https://twitter.com/jarredsumner/status/1499225725492076544) currently (try it yourself!) +- **Speed**. Bun processes start [4x faster than Node.js](https://twitter.com/jarredsumner/status/1499225725492076544). - **TypeScript & JSX support**. You can directly execute `.jsx`, `.ts`, and `.tsx` files; Bun's transpiler converts these to vanilla JavaScript before execution. - **ESM & CommonJS compatibility**. The world is moving towards ES modules (ESM), but millions of packages on npm still require CommonJS. Bun recommends ES modules, but supports CommonJS. - **Web-standard APIs**. Bun implements standard Web APIs like `fetch`, `WebSocket`, and `ReadableStream`. Bun is powered by the JavaScriptCore engine, which is developed by Apple for Safari, so some APIs like [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) and [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) directly use [Safari's implementation](https://github.com/oven-sh/bun/blob/HEAD/src/jsc/bindings/webcore/JSFetchHeaders.cpp). -- **Node.js compatibility**. In addition to supporting Node-style module resolution, Bun aims for full compatibility with built-in Node.js globals (`process`, `Buffer`) and modules (`path`, `fs`, `http`, etc.) _This is an ongoing effort that is not complete._ Refer to the [compatibility page](/runtime/nodejs-compat) for the current status. +- **Node.js compatibility**. In addition to supporting Node-style module resolution, Bun aims for full compatibility with built-in Node.js globals (`process`, `Buffer`) and modules (`path`, `fs`, `http`). _This is an ongoing effort._ See [Node.js compatibility](/runtime/nodejs-compat) for the current status. -Bun is more than a runtime. The long-term goal is to be a cohesive, infrastructural toolkit for building apps with JavaScript/TypeScript, including a package manager, transpiler, bundler, script runner, test runner, and more. +Bun is more than a runtime. The long-term goal is a cohesive, infrastructural toolkit for building apps with JavaScript/TypeScript: a package manager, transpiler, bundler, script runner, and test runner. diff --git a/docs/installation.mdx b/docs/installation.mdx index 8a3c6cb38f01..be6531858e93 100644 --- a/docs/installation.mdx +++ b/docs/installation.mdx @@ -5,7 +5,7 @@ description: Install Bun with npm, Homebrew, Docker, or the official script. ## Overview -Bun ships as a single, dependency-free executable. You can install it via script, package manager, or Docker across macOS, Linux, and Windows. +Bun ships as a single, dependency-free executable. Install it with the install script, a package manager, or Docker on macOS, Linux, and Windows. After installation, verify with `bun --version` and `bun --revision`. @@ -21,7 +21,7 @@ Bun ships as a single, dependency-free executable. You can install it via script
- **Linux users**  The `unzip` package is required to install Bun. Use `sudo apt install unzip` to install the unzip package. Kernel version 5.6 or higher is recommended; Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version. + **Linux users**  The `unzip` package is required to install Bun (`sudo apt install unzip`). Kernel version 5.6 or higher is recommended; Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version.
@@ -38,7 +38,7 @@ Bun ships as a single, dependency-free executable. You can install it via script - For support and discussion, please join the **#windows** channel on our [Discord](https://bun.com/discord). + For support and discussion, join the **#windows** channel on the [Discord](https://bun.com/discord). @@ -71,7 +71,7 @@ Bun ships as a single, dependency-free executable. You can install it via script ### Image Variants - There are also image variants for different operating systems: + Bun also publishes image variants for different operating systems: ```bash Docker icon="docker" docker pull oven/bun:debian @@ -137,7 +137,7 @@ bun --revision & "$env:USERPROFILE\.bun\bin\bun" --version ``` - If the command runs successfully but `bun --version` is not recognized, it means that bun is not in your system's PATH. To fix this, open a Powershell terminal and run the following command: + If the command runs successfully but `bun --version` is not recognized, bun is not in your system's PATH. To fix this, open a PowerShell terminal and run the following command: ```bash terminal icon="terminal" [System.Environment]::SetEnvironmentVariable( @@ -149,7 +149,7 @@ bun --revision - After running the command, restart your terminal and test with `bun --version` + Restart your terminal and test with `bun --version`. ```bash terminal icon="terminal" bun --version @@ -196,7 +196,7 @@ bun upgrade --canary bun upgrade --stable ``` -The canary build is useful for testing new features and bug fixes before they're released in a stable build. To help the Bun team fix bugs faster, canary builds automatically upload crash reports to Bun's team. +Use a canary build to test new features and bug fixes before they reach a stable release. To help the Bun team fix bugs faster, canary builds automatically upload crash reports. --- @@ -308,7 +308,7 @@ For distributions without `glibc` (Alpine Linux, Void Linux): ## CPU Requirements -Bun has specific CPU requirements based on the binary you're using: +CPU requirements depend on which binary you're using: @@ -333,8 +333,8 @@ Bun has specific CPU requirements based on the binary you're using: - Bun does not support CPUs older than the baseline target, which mandates the SSE4.2 extension. macOS requires version - 13.0 or later. + Bun does not support CPUs older than the baseline target, which requires the SSE4.2 extension. Bun requires macOS 13.0 + or later. --- diff --git a/docs/pm/bunx.mdx b/docs/pm/bunx.mdx index b92ef339ad41..3ed14dddf5d7 100644 --- a/docs/pm/bunx.mdx +++ b/docs/pm/bunx.mdx @@ -5,7 +5,7 @@ description: "Run packages from npm" import Bunx from "/snippets/cli/bunx.mdx"; -`bunx` is an alias for `bun x`. The `bunx` CLI will be auto-installed when you install `bun`. +`bunx` is an alias for `bun x`. The `bunx` CLI is auto-installed when you install `bun`. Use `bunx` to auto-install and run packages from `npm`. It's Bun's equivalent of `npx` or `yarn dlx`. @@ -30,7 +30,7 @@ Packages can declare executables in the `"bin"` field of their `package.json`. T } ``` -These executables are commonly plain JavaScript files marked with a [shebang line]() to indicate which program should be used to execute them. The following file indicates that it should be executed with `node`. +These executables are commonly plain JavaScript files marked with a [shebang line]() naming the program that should run them. The following file runs with `node`. ```js dist/index.js icon="/icons/javascript.svg" #!/usr/bin/env node @@ -38,13 +38,13 @@ These executables are commonly plain JavaScript files marked with a [shebang lin console.log("Hello world!"); ``` -These executables can be run with `bunx`, +Run these executables with `bunx`: ```bash terminal icon="terminal" bunx my-cli ``` -As with `npx`, `bunx` will check for a locally installed package first, then fall back to auto-installing the package from `npm`. Installed packages will be stored in Bun's global cache for future use. +As with `npx`, `bunx` checks for a locally installed package first, then falls back to auto-installing it from `npm`. Installed packages are stored in Bun's [global cache](/pm/global-cache) for future use. ## Arguments and flags @@ -58,7 +58,7 @@ bunx my-cli --foo bar ## Shebangs -By default, Bun respects shebangs. If an executable is marked with `#!/usr/bin/env node`, Bun will spin up a `node` process to execute the file. However, in some cases it may be desirable to run executables using Bun's runtime, even if the executable indicates otherwise. To do so, include the `--bun` flag. +By default, Bun respects shebangs. If an executable is marked with `#!/usr/bin/env node`, Bun spins up a `node` process to execute the file. To run the executable with Bun's runtime instead, pass the `--bun` flag. ```bash terminal icon="terminal" bunx --bun my-cli @@ -73,14 +73,14 @@ bunx my-cli --bun # bad ## Package flag -**`--package ` or `-p `** - Run binary from specific package. Useful when binary name differs from package name: +**`--package ` or `-p `** - Run a binary from a specific package. Useful when the binary name differs from the package name: ```bash terminal icon="terminal" bunx -p renovate renovate-config-validator bunx --package @angular/cli ng ``` -To force bun to always be used with a script, use a shebang. +To force a script to always run with Bun, give it a `bun` shebang. ```js dist/index.js icon="/icons/javascript.svg" #!/usr/bin/env bun diff --git a/docs/pm/catalogs.mdx b/docs/pm/catalogs.mdx index 887c7275247b..2fe7f4a5f0eb 100644 --- a/docs/pm/catalogs.mdx +++ b/docs/pm/catalogs.mdx @@ -3,17 +3,17 @@ title: "Catalogs" description: "Share common dependency versions across multiple packages in a monorepo" --- -Catalogs in Bun let you share common dependency versions across multiple packages in a monorepo. Rather than specifying the same versions repeatedly in each workspace package, you define them once in the root package.json and reference them consistently throughout your project. +**Catalogs** share dependency versions across the packages in a monorepo. Rather than repeating the same versions in each workspace package, you define them once in the root `package.json` and reference them throughout your project. ## Overview -Unlike traditional dependency management where each workspace package needs to independently specify versions, catalogs let you: +Instead of each workspace package specifying its own versions, you: -1. Define version catalogs in the root package.json -2. Reference these versions with the `catalog:` protocol -3. Update all packages simultaneously by changing the version in one place +1. Define version catalogs in the root `package.json` +2. Reference those versions with the `catalog:` protocol +3. Update every package at once by changing the version in one place -This is especially useful in large monorepos where dozens of packages need to use the same version of key dependencies. +This matters most in large monorepos where dozens of packages depend on the same versions of key dependencies. ## How to Use Catalogs @@ -57,7 +57,7 @@ In your root-level `package.json`, add a `catalog` or `catalogs` field within th } ``` -If you put `catalog` or `catalogs` at the top level of the `package.json` file, that will work too. +`catalog` and `catalogs` also work at the top level of `package.json`. ### 2. Reference Catalog Versions in Workspace Packages @@ -137,14 +137,14 @@ Bun supports two ways to define catalogs: ## Benefits of Using Catalogs -- **Consistency**: Ensures all packages use the same version of critical dependencies -- **Maintenance**: Update a dependency version in one place instead of across multiple package.json files +- **Consistency**: All packages use the same version of critical dependencies +- **Maintenance**: Update a dependency version in one place instead of across multiple `package.json` files - **Clarity**: Makes it obvious which dependencies are standardized across your monorepo -- **Simplicity**: No need for complex version resolution strategies or external tools +- **Simplicity**: No extra version resolution strategies or external tools ## Real-World Example -Here's a more comprehensive example for a React application: +A larger example, for a React application: **Root package.json** @@ -235,7 +235,7 @@ Then run `bun install` to update all packages. ## Lockfile Integration -Bun's lockfile tracks catalog versions, ensuring consistent installations across different environments. The lockfile includes: +Bun's lockfile tracks catalog versions, so installs are consistent across environments. The lockfile includes: - The catalog definitions from your package.json - The resolution of each cataloged dependency @@ -279,14 +279,12 @@ Bun's lockfile tracks catalog versions, ensuring consistent installations across - Catalog references must match a dependency defined in either `catalog` or one of the named `catalogs` - Empty strings and whitespace in catalog names are ignored (treated as default catalog) -- Invalid dependency versions in catalogs will fail to resolve during `bun install` +- Invalid dependency versions in catalogs fail to resolve during `bun install` - Catalogs are only available within workspaces; they cannot be used outside the monorepo -Bun's catalog system maintains consistency across your monorepo without introducing additional complexity to your workflow. - ## Publishing -When you run `bun publish` or `bun pm pack`, Bun automatically replaces -`catalog:` references in your `package.json` with the resolved version numbers. -The published package includes regular semver strings and no longer depends on -your catalog definitions. +When you run `bun publish` or `bun pm pack`, Bun replaces `catalog:` references +in your `package.json` with the resolved version numbers. The published package +includes regular semver strings and no longer depends on your catalog +definitions. diff --git a/docs/pm/cli/add.mdx b/docs/pm/cli/add.mdx index f699951d377b..97cd6031a1c5 100644 --- a/docs/pm/cli/add.mdx +++ b/docs/pm/cli/add.mdx @@ -50,14 +50,14 @@ bun add --peer @types/bun **Alias** — `-E` -To add a package and pin to the resolved version, use `--exact`. This will resolve the version of the package and add it to your `package.json` with an exact version number instead of a version range. +To pin a package to the resolved version, use `--exact`. Bun writes the exact version number to your `package.json` instead of a version range. ```bash terminal icon="terminal" bun add react --exact bun add react -E ``` -This will add the following to your `package.json`: +The difference in `package.json`: ```json package.json icon="file-json" { @@ -79,12 +79,9 @@ bun add --help ## `--global` - - **Note** — This would not modify package.json of your current project folder. **Alias** - `bun add --global`, `bun add - -g`, `bun install --global` and `bun install -g` - +**Alias** — `bun add --global`, `bun add -g`, `bun install --global` and `bun install -g` -To install a package globally, use the `-g`/`--global` flag. This will not modify the `package.json` of your current project. Typically this is used for installing command-line tools. +To install a package globally, use the `-g`/`--global` flag. This does not modify the `package.json` of your current project. Use it to install command-line tools. ```bash terminal icon="terminal" bun add --global cowsay # or `bun add -g cowsay` @@ -129,7 +126,7 @@ To tell Bun to allow lifecycle scripts for a particular package, add the package } ``` -Bun reads this field and will run lifecycle scripts for `my-trusted-package`. +Bun reads this field and runs lifecycle scripts for `my-trusted-package`. ## Git dependencies @@ -143,7 +140,7 @@ bun add git@github.com:moment/moment.git To install private repositories, your system needs the appropriate SSH credentials to access the repository. -Bun supports a variety of protocols, including [`github`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#github-urls), [`git`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#git-urls-as-dependencies), `git+ssh`, `git+https`, and many more. +Bun supports a variety of protocols, including [`github`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#github-urls), [`git`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#git-urls-as-dependencies), `git+ssh`, and `git+https`. ```json package.json icon="file-json" { @@ -158,13 +155,13 @@ Bun supports a variety of protocols, including [`github`](https://docs.npmjs.com ## Tarball dependencies -A package name can correspond to a publicly hosted `.tgz` file. During installation, Bun will download and install the package from the specified tarball URL, rather than from the package registry. +A package name can correspond to a publicly hosted `.tgz` file. Bun downloads and installs the package from that tarball URL rather than from the package registry. ```sh terminal icon="terminal" bun add zod@https://registry.npmjs.org/zod/-/zod-3.21.4.tgz ``` -This will add the following line to your `package.json`: +`bun add` writes the URL to your `package.json`: ```json package.json icon="file-json" { diff --git a/docs/pm/cli/audit.mdx b/docs/pm/cli/audit.mdx index ce387d94e656..0038c4997aa9 100644 --- a/docs/pm/cli/audit.mdx +++ b/docs/pm/cli/audit.mdx @@ -9,7 +9,7 @@ Run the command in a project with a `bun.lock` file: bun audit ``` -Bun sends the list of installed packages and versions to NPM, and prints a report of any vulnerabilities that were found. Packages installed from registries other than the default registry are skipped. +Bun sends the list of installed packages and versions to npm, and prints a report of any vulnerabilities found. Packages installed from registries other than the default registry are skipped. If no vulnerabilities are found, the command prints: @@ -17,7 +17,7 @@ If no vulnerabilities are found, the command prints: No vulnerabilities found ``` -When vulnerabilities are detected, each affected package is listed along with the severity, a short description and a link to the advisory. At the end of the report Bun prints a summary and hints for updating: +When vulnerabilities are detected, Bun lists each affected package with the severity, a short description, and a link to the advisory. At the end of the report it prints a summary and hints for updating: ``` 3 vulnerabilities (1 high, 2 moderate) @@ -41,7 +41,7 @@ bun audit --audit-level=high bun audit --prod ``` -**`--ignore `** - Ignore specific CVEs (can be used multiple times): +**`--ignore `** - Ignore specific CVEs (repeat the flag to ignore several): ```bash terminal icon="terminal" bun audit --ignore CVE-2022-25883 --ignore CVE-2023-26136 @@ -57,4 +57,4 @@ bun audit --json ### Exit code -`bun audit` will exit with code `0` if no vulnerabilities are found and `1` if the report lists any vulnerabilities. This will still happen even if `--json` is passed. +`bun audit` exits with code `0` if no vulnerabilities are found and `1` if the report lists any, including when `--json` is passed. diff --git a/docs/pm/cli/info.mdx b/docs/pm/cli/info.mdx index 9e4feb135293..b8aba2fa67c9 100644 --- a/docs/pm/cli/info.mdx +++ b/docs/pm/cli/info.mdx @@ -11,7 +11,7 @@ description: "Display package metadata from the npm registry" bun info react ``` -This will display information about the `react` package, including its latest version, description, homepage, dependencies, and more. +`bun info react` prints the package's latest version, description, homepage, dependencies, and other metadata. ## Viewing specific versions @@ -23,7 +23,7 @@ bun info react@18.0.0 ## Viewing specific properties -You can also query specific properties from the package metadata: +To print specific properties from the package metadata: ```bash terminal icon="terminal" bun info react version diff --git a/docs/pm/cli/install.mdx b/docs/pm/cli/install.mdx index 0e2a092d549e..6782304a3c9d 100644 --- a/docs/pm/cli/install.mdx +++ b/docs/pm/cli/install.mdx @@ -13,7 +13,7 @@ bun install react@19.1.1 # specific version bun install react@latest # specific tag ``` -The `bun` CLI contains a Node.js-compatible package manager designed to be a dramatically faster replacement for `npm`, `yarn`, and `pnpm`. It's a standalone tool that will work in pre-existing Node.js projects; if your project has a `package.json`, `bun install` can help you speed up your workflow. +The `bun` CLI contains a Node.js-compatible package manager designed to be a dramatically faster replacement for `npm`, `yarn`, and `pnpm`. It's a standalone tool that works in existing Node.js projects; if your project has a `package.json`, you can use `bun install`. @@ -32,11 +32,11 @@ To install all dependencies of a project: bun install ``` -Running `bun install` will: +`bun install`: -- **Install** all `dependencies`, `devDependencies`, and `optionalDependencies`. Bun will install `peerDependencies` by default. -- **Run** your project's `{pre|post}install` and `{pre|post}prepare` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies. -- **Write** a `bun.lock` lockfile to the project root. +- **Installs** all `dependencies`, `devDependencies`, and `optionalDependencies`. Bun installs `peerDependencies` by default. +- **Runs** your project's `{pre|post}install` and `{pre|post}prepare` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies. +- **Writes** a `bun.lock` lockfile to the project root. --- @@ -65,15 +65,15 @@ To tell Bun to allow lifecycle scripts for a particular package, add the package } ``` -Then re-install the package. Bun will read this field and run lifecycle scripts for `my-trusted-package`. +Then re-install the package. Bun reads this field and runs lifecycle scripts for `my-trusted-package`. -Lifecycle scripts will run in parallel during installation. To adjust the maximum number of concurrent scripts, use the `--concurrent-scripts` flag. The default is two times the reported cpu count or GOMAXPROCS. +Lifecycle scripts run in parallel during installation. To adjust the maximum number of concurrent scripts, use the `--concurrent-scripts` flag. The default is two times the reported cpu count or GOMAXPROCS. ```bash terminal icon="terminal" bun install --concurrent-scripts 5 ``` -Bun automatically optimizes postinstall scripts for popular packages (like `esbuild`, `sharp`, etc.) by determining which scripts need to run. To disable these optimizations: +Bun automatically optimizes postinstall scripts for popular packages (like `esbuild` and `sharp`) by determining which scripts need to run. To disable these optimizations: ```bash terminal icon="terminal" BUN_FEATURE_FLAG_DISABLE_NATIVE_DEPENDENCY_LINKER=1 bun install @@ -84,7 +84,7 @@ BUN_FEATURE_FLAG_DISABLE_IGNORE_SCRIPTS=1 bun install ## Workspaces -Bun supports `"workspaces"` in package.json. For complete documentation refer to [Package manager > Workspaces](/pm/workspaces). +Bun supports `"workspaces"` in package.json. See [workspaces](/pm/workspaces). ```json package.json icon="file-json" { @@ -111,13 +111,13 @@ bun install --filter '!pkg-c' bun install --filter './packages/pkg-a' ``` -For more information on filtering with `bun install`, refer to [Package Manager > Filtering](/pm/filter#bun-install-and-bun-outdated) +See [filtering](/pm/filter#bun-install-and-bun-outdated). --- ## Overrides and resolutions -Bun supports npm's `"overrides"` and Yarn's `"resolutions"` in `package.json`. These are mechanisms for specifying a version range for _metadependencies_—the dependencies of your dependencies. Refer to [Package manager > Overrides and resolutions](/pm/overrides) for complete documentation. +Bun supports npm's `"overrides"` and Yarn's `"resolutions"` in `package.json`. Both specify a version range for _metadependencies_, the dependencies of your dependencies. See [overrides and resolutions](/pm/overrides). {/* prettier-ignore */} ```json package.json icon="file-json" @@ -136,7 +136,7 @@ Bun supports npm's `"overrides"` and Yarn's `"resolutions"` in `package.json`. T ## Global packages -To install a package globally, use the `-g`/`--global` flag. Typically this is used for installing command-line tools. +To install a package globally, use the `-g`/`--global` flag. Use it to install command-line tools. ```bash terminal icon="terminal" bun install --global cowsay # or `bun install -g cowsay` @@ -158,25 +158,25 @@ cowsay "Bun!" ## Production mode -To install in production mode (i.e. without `devDependencies` or `optionalDependencies`): +To install in production mode (without `devDependencies` or `optionalDependencies`): ```bash terminal icon="terminal" bun install --production ``` -For reproducible installs, use `--frozen-lockfile`. This will install the exact versions of each package specified in the lockfile. If your `package.json` disagrees with `bun.lock`, Bun will exit with an error. The lockfile will not be updated. +For reproducible installs, use `--frozen-lockfile`. Bun installs the exact versions specified in the lockfile and does not update it. If your `package.json` disagrees with `bun.lock`, Bun exits with an error. ```bash terminal icon="terminal" bun install --frozen-lockfile ``` -For more information on Bun's lockfile `bun.lock`, refer to [Package manager > Lockfile](/pm/lockfile). +See [lockfile](/pm/lockfile) for more on `bun.lock`. --- ## Omitting dependencies -To omit dev, peer, or optional dependencies use the `--omit` flag. +To omit dev, peer, or optional dependencies, use the `--omit` flag. ```bash terminal icon="terminal" # Exclude "devDependencies" from the installation. This will apply to the @@ -192,7 +192,7 @@ bun install --omit=dev --omit=peer --omit=optional ## Dry run -To perform a dry run (i.e. don't actually install anything): +To perform a dry run, without installing anything: ```bash terminal icon="terminal" bun install --dry-run @@ -202,7 +202,7 @@ bun install --dry-run ## Non-npm dependencies -Bun supports installing dependencies from Git, GitHub, and local or remotely-hosted tarballs. For complete documentation refer to [Package manager > Git, GitHub, and tarball dependencies](/pm/cli/add). +Bun supports installing dependencies from Git, GitHub, and local or remotely-hosted tarballs. See [`bun add`](/pm/cli/add). ```json package.json icon="file-json" { @@ -233,7 +233,7 @@ bun install --linker hoisted ### Isolated installs -A pnpm-like approach that creates strict dependency isolation to prevent phantom dependencies: +A pnpm-like approach that creates strict dependency isolation to prevent [phantom dependencies](/pm/isolated-installs), packages that can be imported without being declared in `package.json`: ```bash terminal icon="terminal" bun install --linker isolated @@ -249,13 +249,13 @@ The default linker strategy depends on whether you're starting fresh or have an - **New single-package projects**: `hoisted` (traditional npm behavior) - **Existing projects (made pre-v1.3.2)**: `hoisted` (preserves backward compatibility) -The default is controlled by a `configVersion` field in your lockfile. For a detailed explanation, see [Package manager > Isolated installs](/pm/isolated-installs). +The default is controlled by a `configVersion` field in your lockfile. For a detailed explanation, see [isolated installs](/pm/isolated-installs). --- ## Minimum release age -To protect against supply chain attacks where malicious packages are quickly published, you can configure a minimum age requirement for npm packages. Package versions published more recently than the specified threshold (in seconds) will be filtered out during installation. +To protect against supply chain attacks where malicious packages are quickly published, you can configure a minimum age requirement for npm packages. Bun filters out package versions published more recently than the specified threshold (in seconds) during installation. ```bash terminal icon="terminal" # Only install package versions published at least 3 days ago @@ -275,15 +275,15 @@ minimumReleaseAgeExcludes = ["@types/node", "typescript"] When the minimum age filter is active: -- Only affects new package resolution - existing packages in `bun.lock` remain unchanged -- All dependencies (direct and transitive) are filtered to meet the age requirement when being resolved +- It only affects new package resolution; existing packages in `bun.lock` remain unchanged +- All dependencies (direct and transitive) are filtered to meet the age requirement when resolved - When versions are blocked by the age gate, a stability check detects rapid bugfix patterns - - If multiple versions were published close together just outside your age gate, it extends the filter to skip those potentially unstable versions and selects an older, more mature version - - Searches up to 7 days after the age gate, however if still finding rapid releases it ignores stability check + - If multiple versions were published close together just outside your age gate, Bun extends the filter to skip those potentially unstable versions and selects an older, more mature version + - The check searches up to 7 days past the age gate; if releases are still rapid beyond that, Bun ignores the stability check - Exact version requests (like `package@1.1.1`) still respect the age gate but bypass the stability check -- Versions without a `time` field are treated as passing the age check (npm registry should always provide timestamps) +- Versions without a `time` field are treated as passing the age check (the npm registry should always provide timestamps) -For more advanced security scanning, including integration with services & custom filtering, see [Package manager > Security Scanner API](/pm/security-scanner-api). +For more advanced security scanning, including integration with services and custom filtering, see the [Security Scanner API](/pm/security-scanner-api). --- @@ -291,14 +291,14 @@ For more advanced security scanning, including integration with services & custo ### Configuring `bun install` with `bunfig.toml` -`bunfig.toml` is searched for in the following paths on `bun install`, `bun remove`, and `bun add`: +On `bun install`, `bun remove`, and `bun add`, Bun looks for `bunfig.toml` in: 1. `$XDG_CONFIG_HOME/.bunfig.toml` or `$HOME/.bunfig.toml` 2. `./bunfig.toml` If both are found, the results are merged together. -Configuring with `bunfig.toml` is optional. Bun tries to be zero configuration in general, but that's not always possible. The default behavior of `bun install` can be configured in `bunfig.toml`. The default values are shown below. +Configuring with `bunfig.toml` is optional. These are the default values: ```toml bunfig.toml icon="settings" [install] @@ -341,7 +341,7 @@ minimumReleaseAgeExcludes = ["@types/node", "typescript"] ### Configuring with environment variables -Environment variables have a higher priority than `bunfig.toml`. +Environment variables take priority over `bunfig.toml`. | Name | Description | | ---------------------------------- | ------------------------------------------------------------- | @@ -353,15 +353,15 @@ Environment variables have a higher priority than `bunfig.toml`. | `BUN_CONFIG_SKIP_LOAD_LOCKFILE` | Don’t load a lockfile | | `BUN_CONFIG_SKIP_INSTALL_PACKAGES` | Don’t install any packages | -Bun always tries to use the fastest available installation method for the target platform. On macOS, that’s `clonefile` and on Linux, that’s `hardlink`. You can change which installation method is used with the `--backend` flag. When unavailable or on error, `clonefile` and `hardlink` fallsback to a platform-specific implementation of copying files. +Bun uses the fastest installation method available on the target platform: `clonefile` on macOS and `hardlink` on Linux. You can change the installation method with the `--backend` flag. When unavailable or on error, `clonefile` and `hardlink` fall back to a platform-specific implementation of copying files. -Bun stores installed packages from npm in `~/.bun/install/cache/${name}@${version}`. Note that if the semver version has a `build` or a `pre` tag, it is replaced with a hash of that value instead. This is to reduce the chances of errors from long file paths, but unfortunately complicates figuring out where a package was installed on disk. +Bun stores installed packages from npm in `~/.bun/install/cache/${name}@${version}`. If the semver version has a `build` or a `pre` tag, Bun replaces it with a hash of that value. This reduces the chances of errors from long file paths, but complicates figuring out where a package was installed on disk. -When the `node_modules` folder exists, before installing, Bun checks if the `"name"` and `"version"` in `package/package.json` in the expected node_modules folder matches the expected `name` and `version`. This is how it determines whether it should install. It uses a custom JSON parser which stops parsing as soon as it finds `"name"` and `"version"`. +When the `node_modules` folder exists, Bun decides whether to install a package by checking that the `"name"` and `"version"` in its `package.json` at the expected `node_modules` location match the expected name and version. It uses a custom JSON parser which stops parsing as soon as it finds `"name"` and `"version"`. -When a `bun.lock` doesn’t exist or `package.json` has changed dependencies, tarballs are downloaded & extracted eagerly while resolving. +When a `bun.lock` doesn’t exist or `package.json` has changed dependencies, Bun downloads and extracts tarballs eagerly while resolving. -When a `bun.lock` exists and `package.json` hasn’t changed, Bun downloads missing dependencies lazily. If the package with a matching `name` & `version` already exists in the expected location within `node_modules`, Bun won’t attempt to download the tarball. +When a `bun.lock` exists and `package.json` hasn’t changed, Bun downloads missing dependencies lazily. If the package with a matching `name` and `version` already exists in the expected location within `node_modules`, Bun won’t attempt to download the tarball. ## CI/CD @@ -390,9 +390,9 @@ For CI/CD environments that want to enforce reproducible builds, use `bun ci` to bun ci ``` -This is equivalent to `bun install --frozen-lockfile`. It installs exact versions from `bun.lock` and fails if `package.json` doesn't match the lockfile. To use `bun ci` or `bun install --frozen-lockfile`, you must commit `bun.lock` to version control. +`bun ci` is equivalent to `bun install --frozen-lockfile`. It installs exact versions from `bun.lock` and fails if `package.json` doesn't match the lockfile. To use `bun ci` or `bun install --frozen-lockfile`, you must commit `bun.lock` to version control. -And instead of running `bun install`, run `bun ci`. +In your workflow, run `bun ci` instead of `bun install`: ```yaml .github/workflows/release.yml icon="file-code" name: bun-types @@ -413,7 +413,7 @@ jobs: ## Platform-specific dependencies? -bun stores normalized `cpu` and `os` values from npm in the lockfile, along with the resolved packages. It skips downloading, extracting, and installing packages disabled for the current target at runtime. This means the lockfile won't change between platforms/architectures even if the packages ultimately installed do change. +Bun stores normalized `cpu` and `os` values from npm in the lockfile, along with the resolved packages. It skips downloading, extracting, and installing packages disabled for the current target at runtime. This means the lockfile won't change between platforms/architectures even if the packages ultimately installed do change. ### `--cpu` and `--os` flags @@ -423,7 +423,7 @@ You can override the target platform for package selection: bun install --cpu=x64 --os=linux ``` -This installs packages for the specified platform instead of the current system. Useful for cross-platform builds or when preparing deployments for different environments. +These flags install packages for the specified platform instead of the current system. Use them for cross-platform builds or when preparing deployments for different environments. **Accepted values for `--cpu`**: `arm64`, `x64`, `ia32`, `ppc64`, `s390x` @@ -431,13 +431,13 @@ This installs packages for the specified platform instead of the current system. ## Peer dependencies? -Peer dependencies are handled similarly to yarn. `bun install` will automatically install peer dependencies. If the dependency is marked optional in `peerDependenciesMeta`, an existing dependency will be chosen if possible. +Bun handles peer dependencies like Yarn: `bun install` installs them automatically. If the dependency is marked optional in `peerDependenciesMeta`, Bun uses an existing dependency if possible. ## Lockfile -`bun.lock` is Bun’s lockfile format. See [our blogpost about the text lockfile](https://bun.com/blog/bun-lock-text-lockfile). +`bun.lock` is Bun’s lockfile format. See [our blog post about the text lockfile](https://bun.com/blog/bun-lock-text-lockfile). -Prior to Bun 1.2, the lockfile was binary and called `bun.lockb`. Old lockfiles can be upgraded to the new format by running `bun install --save-text-lockfile --frozen-lockfile --lockfile-only`, and then deleting `bun.lockb`. +Prior to Bun 1.2, the lockfile was binary and called `bun.lockb`. To upgrade an old lockfile to the new format, run `bun install --save-text-lockfile --frozen-lockfile --lockfile-only`, then delete `bun.lockb`. ## Cache @@ -451,7 +451,7 @@ rm -rf ~/.bun/install/cache ## Platform-specific backends -`bun install` uses different system calls to install dependencies depending on the platform. This is a performance optimization. You can force a specific backend with the `--backend` flag. +For performance, `bun install` uses different system calls to install dependencies depending on the platform. You can force a specific backend with the `--backend` flag. **`hardlink`** is the default backend on Linux. Benchmarking showed it to be the fastest on Linux. @@ -474,7 +474,7 @@ rm -rf node_modules bun install --backend clonefile_each_dir ``` -**`copyfile`** is the fallback used when any of the above fail, and is the slowest. on macOS, it uses `fcopyfile()` and on linux it uses `copy_file_range()`. +**`copyfile`** is the fallback used when any of the above fail, and is the slowest. On macOS, it uses `fcopyfile()`; on Linux, it uses `copy_file_range()`. ```bash rm -rf node_modules @@ -494,20 +494,20 @@ node --preserve-symlinks ./my-file.js # https://nodejs.org/api/cli.html#--preser ## npm registry metadata -Bun uses a binary format for caching NPM registry responses. This loads much faster than JSON and tends to be smaller on disk. -You will see these files in `~/.bun/install/cache/*.npm`. The filename pattern is `${hash(packageName)}.npm`. It’s a hash so that extra directories don’t need to be created for scoped packages. +Bun uses a binary format for caching npm registry responses. This loads much faster than JSON and tends to be smaller on disk. +These files live in `~/.bun/install/cache/*.npm`. The filename pattern is `${hash(packageName)}.npm`. It’s a hash so that extra directories don’t need to be created for scoped packages. -Bun's usage of `Cache-Control` ignores `Age`. This improves performance, but means bun may be about 5 minutes out of date to receive the latest package version metadata from npm. +Bun's usage of `Cache-Control` ignores `Age`. This improves performance, but means Bun may be about 5 minutes behind the latest package version metadata from npm. ## pnpm migration -Bun automatically migrates projects from pnpm to bun. When a `pnpm-lock.yaml` file is detected and no `bun.lock` file exists, Bun will automatically migrate the lockfile to `bun.lock` during installation. The original `pnpm-lock.yaml` file remains unmodified. +Bun migrates projects from pnpm automatically. When a `pnpm-lock.yaml` file is detected and no `bun.lock` file exists, Bun converts the lockfile to `bun.lock` during installation. The original `pnpm-lock.yaml` file remains unmodified. ```bash terminal icon="terminal" bun install ``` -**Note**: Migration only runs when `bun.lock` is absent. There is currently no opt-out flag for pnpm migration. +Migration only runs when `bun.lock` is absent. There is currently no opt-out flag for pnpm migration. The migration process handles: @@ -537,7 +537,7 @@ catalogs: babel: ^7.0.0 ``` -The workspace packages list and catalogs are moved to the `workspaces` field in `package.json`: +Bun moves the workspace packages list and catalogs to the `workspaces` field in `package.json`: ```json package.json icon="file-json" { @@ -572,7 +572,7 @@ Dependencies using pnpm's `catalog:` protocol are preserved: ### Configuration Migration -The following pnpm configuration is migrated from both `pnpm-lock.yaml` and `pnpm-workspace.yaml`: +Bun migrates the following pnpm configuration from both `pnpm-lock.yaml` and `pnpm-workspace.yaml`: - **Overrides**: Moved from `pnpm.overrides` to root-level `overrides` in `package.json` - **Patched Dependencies**: Moved from `pnpm.patchedDependencies` to root-level `patchedDependencies` in `package.json` diff --git a/docs/pm/cli/link.mdx b/docs/pm/cli/link.mdx index b0b46314aad0..7341bacb5256 100644 --- a/docs/pm/cli/link.mdx +++ b/docs/pm/cli/link.mdx @@ -24,14 +24,14 @@ Or add it in dependencies in your package.json file: "cool-pkg": "link:cool-pkg" ``` -This package can now be "linked" into other projects using `bun link cool-pkg`. This will create a symlink in the `node_modules` directory of the target project, pointing to the local directory. +This package can now be "linked" into other projects using `bun link cool-pkg`, which creates a symlink in the target project's `node_modules` directory pointing to the local directory. ```bash terminal icon="terminal" cd /path/to/my-app bun link cool-pkg ``` -In addition, the `--save` flag can be used to add `cool-pkg` to the `dependencies` field of your app's package.json with a special version specifier that tells Bun to load from the registered local directory instead of installing from `npm`: +The `--save` flag also adds `cool-pkg` to the `dependencies` field of your app's package.json, with a version specifier that tells Bun to load from the registered local directory instead of installing from `npm`: ```json package.json icon="file-json" { diff --git a/docs/pm/cli/outdated.mdx b/docs/pm/cli/outdated.mdx index bf62b03a060e..5ea6f4ad4ad3 100644 --- a/docs/pm/cli/outdated.mdx +++ b/docs/pm/cli/outdated.mdx @@ -5,7 +5,7 @@ description: "Check for outdated dependencies" import Outdated from "/snippets/cli/outdated.mdx"; -Use `bun outdated` to check for outdated dependencies in your project. This command displays a table of dependencies that have newer versions available. +`bun outdated` displays a table of the dependencies in your project that have newer versions available. ```sh terminal icon="terminal" bun outdated @@ -36,9 +36,7 @@ The output table shows three version columns: ### Dependency Filters -`bun outdated` supports searching for outdated dependencies by package names and glob patterns. - -To check if specific dependencies are outdated, pass the package names as positional arguments: +To check specific dependencies, pass their names as positional arguments: ```sh terminal icon="terminal" bun outdated eslint-plugin-security eslint-plugin-sonarjs @@ -52,7 +50,7 @@ bun outdated eslint-plugin-security eslint-plugin-sonarjs ``` -You can also pass glob patterns to check for outdated packages: +Glob patterns work too: ```sh terminal icon="terminal" bun outdated 'eslint*' @@ -112,7 +110,7 @@ bun outdated --filter='@monorepo/types' | typescript (dev) | 5.7.2 | 5.7.3 | 5.7.3 | ``` -You can pass multiple `--filter` flags to check multiple workspaces: +Pass `--filter` more than once to check multiple workspaces: ```sh terminal icon="terminal" bun outdated --filter @monorepo/types --filter @monorepo/cli @@ -129,7 +127,7 @@ bun outdated --filter @monorepo/types --filter @monorepo/cli | typescript (dev) | 5.7.2 | 5.7.3 | 5.7.3 | ``` -You can also pass glob patterns to filter by workspace names: +`--filter` also accepts glob patterns for workspace names: ```sh terminal icon="terminal" bun outdated --filter='@monorepo/{types,cli}' @@ -148,7 +146,7 @@ bun outdated --filter='@monorepo/{types,cli}' ### Catalog Dependencies -`bun outdated` supports checking catalog dependencies defined in`package.json`: +`bun outdated` also checks [catalog](/pm/catalogs) dependencies defined in `package.json`: ```sh terminal icon="terminal" bun outdated -r diff --git a/docs/pm/cli/patch.mdx b/docs/pm/cli/patch.mdx index 27dc4b3255e9..faa3878e98f6 100644 --- a/docs/pm/cli/patch.mdx +++ b/docs/pm/cli/patch.mdx @@ -5,22 +5,22 @@ description: "Persistently patch node_modules packages in a git-friendly way" import Patch from "/snippets/cli/patch.mdx"; -`bun patch` lets you persistently patch node_modules in a maintainable, git-friendly way. +`bun patch` persistently patches packages in `node_modules` in a maintainable, git-friendly way. -Sometimes, you need to make a small change to a package in `node_modules/` to fix a bug or add a feature. `bun patch` lets you do this without vendoring the entire package and reuse the patch across multiple installs, multiple projects, and multiple machines. +Sometimes you need a small change to a package in `node_modules/` to fix a bug or add a feature. `bun patch` lets you do this without vendoring the entire package. Features: -- Generates `.patch` files applied to dependencies in `node_modules` on install -- `.patch` files can be committed to your repository, reused across multiple installs, projects, and machines +- Generates `.patch` files that Bun applies to dependencies in `node_modules` on install +- `.patch` files can be committed to your repository and reused across installs, projects, and machines - `"patchedDependencies"` in `package.json` keeps track of patched packages -- `bun patch` lets you patch packages in `node_modules/` while preserving the integrity of Bun's [Global Cache](/pm/global-cache) +- Patches packages in `node_modules/` while preserving the integrity of Bun's [Global Cache](/pm/global-cache) - Test your changes locally before committing them with `bun patch --commit ` - To preserve disk space and keep `bun install` fast, patched packages are committed to the Global Cache and shared across projects where possible #### Step 1. Prepare the package for patching -To get started, use `bun patch ` to prepare the package for patching: +Use `bun patch ` to prepare the package for patching: ```bash terminal icon="terminal" # you can supply the package name @@ -34,21 +34,21 @@ bun patch node_modules/react ``` -Don't forget to call `bun patch `! This ensures the package folder in `node_modules/` contains a fresh copy of the package with no symlinks/hardlinks to Bun's cache. +Don't skip `bun patch `. It ensures the package folder in `node_modules/` contains a fresh copy of the package with no symlinks or hardlinks to Bun's cache. -If you forget to do this, you might end up editing the package globally in the cache! +If you skip it, you might end up editing the package globally in the cache. #### Step 2. Test your changes locally -`bun patch ` makes it safe to edit the `` in `node_modules/` directly, while preserving the integrity of Bun's [Global Cache](/pm/global-cache). This works by re-creating an unlinked clone of the package in `node_modules/` and diffing it against the original package in the Global Cache. +`bun patch ` makes it safe to edit `` in `node_modules/` directly, while preserving the integrity of Bun's [Global Cache](/pm/global-cache). It works by re-creating an unlinked clone of the package in `node_modules/` and diffing it against the original package in the Global Cache. #### Step 3. Commit your changes Once you're happy with your changes, run `bun patch --commit `. -Bun will generate a patch file in `patches/`, update your `package.json` and lockfile, and Bun will start using the patched package: +Bun generates a patch file in `patches/`, updates your `package.json` and lockfile, and starts using the patched package: ```bash terminal icon="terminal" # you can supply the path to the patched package diff --git a/docs/pm/cli/pm.mdx b/docs/pm/cli/pm.mdx index ea7e1c5c74e4..3f3b68e2e648 100644 --- a/docs/pm/cli/pm.mdx +++ b/docs/pm/cli/pm.mdx @@ -3,7 +3,7 @@ title: "bun pm" description: "Package manager utilities" --- -The `bun pm` command group provides a set of utilities for working with Bun's package manager. +The `bun pm` command group is a set of utilities for working with Bun's package manager. ## pack @@ -13,7 +13,7 @@ To create a tarball of the current workspace: bun pm pack ``` -This command creates a `.tgz` file containing all files that would be published to npm, following the same rules as `npm pack`. +`bun pm pack` creates a `.tgz` file containing all files that would be published to npm, following the same rules as `npm pack`. ## Examples @@ -45,11 +45,11 @@ bun pm pack --destination ./dist ## Options - `--dry-run`: Perform all tasks except writing the tarball to disk. Shows what would be included. -- `--destination `: Specify the directory where the tarball will be saved. -- `--filename `: Specify an exact file name for the tarball to be saved at. +- `--destination `: The directory to save the tarball in. +- `--filename `: An exact file name for the tarball. - `--ignore-scripts`: Skip running pre/postpack and prepare scripts. -- `--gzip-level <0-9>`: Set a custom compression level for gzip, ranging from 0 to 9 (default is 9). -- `--quiet`: Only output the tarball filename, suppressing verbose output. Ideal for scripts and automation. +- `--gzip-level <0-9>`: Set the gzip compression level, from 0 to 9 (default 9). +- `--quiet`: Print only the tarball filename, suppressing the rest of the output. Useful in scripts. > **Note:** `--filename` and `--destination` cannot be used at the same time. @@ -85,8 +85,6 @@ bun pm pack --quiet my-package-1.0.0.tgz ``` -The `--quiet` flag is particularly useful for automation workflows where you need to capture the generated tarball filename for further processing. - ## bin To print the path to the `bin` directory for the local project: @@ -111,7 +109,7 @@ bun pm bin -g ## ls -To print a list of installed dependencies in the current project and their resolved versions, excluding their dependencies. +To print a list of installed dependencies in the current project and their resolved versions, excluding their dependencies: ```bash terminal icon="terminal" bun pm ls @@ -128,7 +126,7 @@ bun list └── zod@3.21.4 ``` -To print all installed dependencies, including nth-order dependencies. +To print all installed dependencies, including nth-order dependencies: ```bash terminal icon="terminal" bun pm ls --all @@ -152,7 +150,7 @@ bun list --all ├── ... ``` -To print only trusted dependencies (those allowed to run lifecycle scripts). When `trustedDependencies` is set in `package.json`, packages from that list are shown; otherwise packages from Bun's [default trusted dependencies](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt) list are shown. +To print only trusted dependencies (those allowed to run [lifecycle scripts](/pm/lifecycle)). When `trustedDependencies` is set in `package.json`, Bun shows the packages from that list; otherwise it shows packages from its [default trusted dependencies](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt) list. ```bash terminal icon="terminal" bun pm ls --trusted @@ -250,7 +248,7 @@ To print the default trusted dependencies list: bun pm default-trusted ``` -see the current list on GitHub [here](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt) +See the [current list on GitHub](https://github.com/oven-sh/bun/blob/main/src/install/default-trusted-dependencies.txt). ## version @@ -298,7 +296,7 @@ bun pm version patch v1.0.1 ``` -Supports `patch`, `minor`, `major`, `premajor`, `preminor`, `prepatch`, `prerelease`, `from-git`, or specific versions like `1.2.3`. By default creates git commit and tag unless `--no-git-tag-version` was used to skip. +Supports `patch`, `minor`, `major`, `premajor`, `preminor`, `prepatch`, `prerelease`, `from-git`, or specific versions like `1.2.3`. By default it creates a git commit and tag; pass `--no-git-tag-version` to skip them. ## pkg diff --git a/docs/pm/cli/publish.mdx b/docs/pm/cli/publish.mdx index c316b22dd4bb..8318465382e1 100644 --- a/docs/pm/cli/publish.mdx +++ b/docs/pm/cli/publish.mdx @@ -5,7 +5,7 @@ description: Use `bun publish` to publish a package to the npm registry import Publish from "/snippets/cli/publish.mdx"; -`bun publish` will automatically pack your package into a tarball, strip catalog and workspace protocols from the `package.json` (resolving versions if necessary), and publish to the registry specified in your configuration files. Both `bunfig.toml` and `.npmrc` files are supported. +`bun publish` packs your package into a tarball, strips catalog and workspace protocols from the `package.json` (resolving versions if necessary), and publishes to the registry specified in your configuration files. Both `bunfig.toml` and `.npmrc` files are supported. ```sh terminal icon="terminal" ## Publishing the package from the current working directory @@ -32,7 +32,7 @@ Registry: http://localhost:4873/ + publish-1@1.0.0 ``` -Alternatively, you can pack and publish your package separately by using `bun pm pack` followed by `bun publish` with the path to the output tarball. +To pack and publish separately, run `bun pm pack`, then `bun publish` with the path to the output tarball. ```sh terminal icon="terminal" bun pm pack @@ -41,13 +41,13 @@ bun publish ./package.tgz ``` - `bun publish` will not run lifecycle scripts (`prepublishOnly/prepack/prepare/postpack/publish/postpublish`) if a - tarball path is provided. Scripts will only be run if the package is packed by `bun publish`. + `bun publish` does not run lifecycle scripts (`prepublishOnly/prepack/prepare/postpack/publish/postpublish`) if a + tarball path is provided. Scripts run only when `bun publish` packs the package itself. ### `--access` -The `--access` flag can be used to set the access level of the package being published. The access level can be one of `public` or `restricted`. Unscoped packages are always public, and attempting to publish an unscoped package with `--access restricted` will result in an error. +`--access` sets the access level of the package being published, either `public` or `restricted`. Unscoped packages are always public, and publishing an unscoped package with `--access restricted` is an error. ```sh terminal icon="terminal" bun publish --access public @@ -83,7 +83,7 @@ bun publish --tag alpha ### `--dry-run` -The `--dry-run` flag can be used to simulate the publish process without actually publishing the package. This is useful for verifying the contents of the published package without actually publishing the package. +`--dry-run` runs the publish process without publishing the package, so you can verify what would be published. ```sh terminal icon="terminal" bun publish --dry-run @@ -99,11 +99,11 @@ bun publish --tolerate-republish ### `--gzip-level` -Specify the level of gzip compression to use when packing the package. Only applies to `bun publish` without a tarball path argument. Values range from `0` to `9` (default is `9`). +Set the gzip compression level used when packing the package, from `0` to `9` (default `9`). Only applies to `bun publish` without a tarball path argument. ### `--auth-type` -If you have 2FA enabled for your npm account, `bun publish` will prompt you for a one-time password. This can be done through a browser or the CLI. The `--auth-type` flag can be used to tell the npm registry which method you prefer. The possible values are `web` and `legacy`, with `web` being the default. +If you have 2FA enabled for your npm account, `bun publish` prompts you for a one-time password, either through a browser or in the CLI. `--auth-type` tells the npm registry which method you prefer: `web` (the default) or `legacy`. ```sh terminal icon="terminal" bun publish --auth-type legacy @@ -115,15 +115,15 @@ Enter OTP: 123456 ### `--otp` -Provide a one-time password directly to the CLI. If the password is valid, this will skip the extra prompt for a one-time password before publishing. Example usage: +Provide a one-time password directly to the CLI. If the password is valid, `bun publish` skips the extra one-time password prompt before publishing: ```sh terminal icon="terminal" bun publish --otp 123456 ``` - `bun publish` respects the `NPM_CONFIG_TOKEN` environment variable which can be used when publishing in github actions - or automated workflows. + `bun publish` respects the `NPM_CONFIG_TOKEN` environment variable, useful when publishing from GitHub Actions or + other automated workflows. --- diff --git a/docs/pm/cli/update.mdx b/docs/pm/cli/update.mdx index edc81203f872..81da5c64f0ed 100644 --- a/docs/pm/cli/update.mdx +++ b/docs/pm/cli/update.mdx @@ -21,14 +21,14 @@ bun update [package] ## `--interactive` -For a more controlled update experience, use the `--interactive` flag to select which packages to update: +Use the `--interactive` flag to choose which packages to update: ```sh terminal icon="terminal" bun update --interactive bun update -i ``` -This launches an interactive terminal interface that shows all outdated packages with their current and target versions. You can then select which packages to update. +The flag opens a terminal interface that lists every outdated package with its current and target versions. ### Interactive Interface @@ -56,7 +56,7 @@ The interface displays packages grouped by dependency type: **Columns:** -- **Package**: Package name (may have suffix like ` dev`, ` peer`, ` optional` for clarity) +- **Package**: Package name (may have a suffix such as ` dev`, ` peer`, or ` optional`) - **Current**: Currently installed version - **Target**: Version that would be installed (respects semver constraints) - **Latest**: Latest available version @@ -97,7 +97,7 @@ Packages are organized in sections by dependency type: - **peerDependencies** - Peer dependencies - **optionalDependencies** - Optional dependencies -Within each section, individual packages may have additional suffixes (` dev`, ` peer`, ` optional`) for extra clarity. +Within each section, individual packages may have a suffix (` dev`, ` peer`, ` optional`). ## `--recursive` @@ -108,19 +108,19 @@ bun update --interactive --recursive bun update -i -r ``` -This displays an additional "Workspace" column showing which workspace each dependency belongs to. +With `--recursive`, the interface adds a "Workspace" column showing which workspace each dependency belongs to. ## `--latest` -By default, `bun update` will update to the latest version of a dependency that satisfies the version range specified in your `package.json`. +By default, `bun update` updates each dependency to the latest version that satisfies the version range in your `package.json`. -To update to the latest version, regardless of if it's compatible with the current version range, use the `--latest` flag: +To update to the latest version regardless of whether it satisfies that range, use the `--latest` flag: ```sh terminal icon="terminal" bun update --latest ``` -In interactive mode, you can toggle individual packages between their target version (respecting semver) and latest version using the **l** key. +In interactive mode, press **l** to toggle a package between its target version (respecting semver) and the latest version. For example, with the following `package.json`: diff --git a/docs/pm/cli/why.mdx b/docs/pm/cli/why.mdx index 5c835a0cbe80..2091605c8c99 100644 --- a/docs/pm/cli/why.mdx +++ b/docs/pm/cli/why.mdx @@ -3,7 +3,7 @@ title: "bun why" description: "Explain why a package is installed" --- -The `bun why` command explains why a package is installed in your project by showing the dependency chain that led to its installation. +`bun why` explains why a package is installed in your project by showing the dependency chain that led to it. ## Usage @@ -33,7 +33,7 @@ react@18.2.0 └─ my-app@1.0.0 (requires ^18.0.0) ``` -Check why all packages with a specific pattern are installed: +Check why all packages matching a pattern are installed: ```bash terminal icon="terminal" bun why "@types/*" diff --git a/docs/pm/filter.mdx b/docs/pm/filter.mdx index 7d00b41a9f85..802554702fd1 100644 --- a/docs/pm/filter.mdx +++ b/docs/pm/filter.mdx @@ -3,9 +3,9 @@ title: "bun --filter" description: "Select packages by pattern in a monorepo using the --filter flag" --- -The `--filter` (or `-F`) flag is used for selecting packages by pattern in a monorepo. Patterns can be used to match package names or package paths, with full glob syntax support. +The `--filter` (or `-F`) flag selects packages in a monorepo by pattern. Patterns match package names or package paths, with full glob syntax. -Currently `--filter` is supported by `bun install` and `bun outdated`, and can also be used to run scripts for multiple packages at once. +`bun install` and `bun outdated` support `--filter`, and you can use it to run scripts in multiple packages at once. --- @@ -13,19 +13,17 @@ Currently `--filter` is supported by `bun install` and `bun outdated`, and can a ### Package Name `--filter ` -Name patterns select packages based on the package name, as specified in `package.json`. For example, if you have packages `pkg-a`, `pkg-b` and `other`, you can match all packages with `*`, only `pkg-a` and `pkg-b` with `pkg*`, and a specific package by providing the full name of the package. +Name patterns select packages by the `name` field in `package.json`. For example, if you have packages `pkg-a`, `pkg-b` and `other`, you can match all of them with `*`, only `pkg-a` and `pkg-b` with `pkg*`, and a specific package with its full name. ### Package Path `--filter ./` -Path patterns are specified by starting the pattern with `./`, and will select all packages in directories that match the pattern. For example, to match all packages in subdirectories of `packages`, you can use `--filter './packages/**'`. To match a package located in `packages/foo`, use `--filter ./packages/foo`. +Path patterns start with `./` and select all packages in directories matching the pattern. For example, to match all packages in subdirectories of `packages`, use `--filter './packages/**'`. To match the package in `packages/foo`, use `--filter ./packages/foo`. --- ## `bun install` and `bun outdated` -Both `bun install` and `bun outdated` support the `--filter` flag. - -`bun install` by default will install dependencies for all packages in the monorepo. To install dependencies for specific packages, use `--filter`. +By default, `bun install` installs dependencies for every package in the monorepo. To install dependencies for specific packages, use `--filter`. Given a monorepo with workspaces `pkg-a`, `pkg-b`, and `pkg-c` under `./packages`: @@ -40,7 +38,7 @@ bun install --filter './packages/*' bun install --filter '!./' --filter './packages/*' ``` -Similarly, `bun outdated` will display outdated dependencies for all packages in the monorepo, and `--filter` can be used to restrict the command to a subset of the packages: +Similarly, `bun outdated` displays outdated dependencies for all packages in the monorepo, and `--filter` restricts the command to a subset of them: ```bash terminal icon="terminal" # Display outdated dependencies for workspaces starting with `pkg-` @@ -50,7 +48,7 @@ bun outdated --filter 'pkg-*' bun outdated --filter './' ``` -For more information on both these commands, see [`bun install`](/pm/cli/install) and [`bun outdated`](/pm/cli/outdated). +See [`bun install`](/pm/cli/install) and [`bun outdated`](/pm/cli/outdated). --- @@ -62,7 +60,7 @@ Use the `--filter` flag to execute scripts in multiple packages at once: bun --filter