mirror of
https://github.com/oven-sh/bun
synced 2026-02-02 15:08:46 +00:00
Replace old docs with new docs repo (#24201)
This commit is contained in:
465
docs/bundler/bytecode.mdx
Normal file
465
docs/bundler/bytecode.mdx
Normal file
@@ -0,0 +1,465 @@
|
||||
---
|
||||
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**.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
Enable bytecode caching with the `--bytecode` flag:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
bun build ./index.ts --target=bun --bytecode --outdir=./dist
|
||||
```
|
||||
|
||||
This generates two files:
|
||||
|
||||
- `dist/index.js` - Your bundled JavaScript
|
||||
- `dist/index.jsc` - The bytecode cache file
|
||||
|
||||
At runtime, Bun automatically detects and uses the `.jsc` file:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
bun ./dist/index.js # Automatically uses index.jsc
|
||||
```
|
||||
|
||||
### With standalone executables
|
||||
|
||||
When creating executables with `--compile`, bytecode is embedded into the binary:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
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.
|
||||
|
||||
### Combining with other optimizations
|
||||
|
||||
Bytecode works great with minification and source maps:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
bun build --compile --bytecode --minify --sourcemap ./cli.ts --outfile=mycli
|
||||
```
|
||||
|
||||
- `--minify` reduces code size before generating bytecode (less code -> less bytecode)
|
||||
- `--sourcemap` preserves error reporting (errors still point to original source)
|
||||
- `--bytecode` eliminates parsing overhead
|
||||
|
||||
## Performance impact
|
||||
|
||||
The performance improvement scales with your codebase size:
|
||||
|
||||
| Application size | Typical startup improvement |
|
||||
| ------------------------- | --------------------------- |
|
||||
| Small CLI (< 100 KB) | 1.5-2x faster |
|
||||
| Medium-large app (> 5 MB) | 2.5x-4x faster |
|
||||
|
||||
Larger applications benefit more because they have more code to parse.
|
||||
|
||||
## When to use bytecode
|
||||
|
||||
### Great for:
|
||||
|
||||
#### CLI tools
|
||||
|
||||
- Invoked frequently (linters, formatters, git hooks)
|
||||
- Startup time is the entire user experience
|
||||
- Users notice the difference between 90ms and 45ms startup
|
||||
- Example: TypeScript compiler, Prettier, ESLint
|
||||
|
||||
#### Build tools and task runners
|
||||
|
||||
- Run hundreds or thousands of times during development
|
||||
- Milliseconds saved per run compound quickly
|
||||
- Developer experience improvement
|
||||
- Example: Build scripts, test runners, code generators
|
||||
|
||||
#### Standalone executables
|
||||
|
||||
- Distributed to users who care about snappy performance
|
||||
- Single-file distribution is convenient
|
||||
- File size less important than startup time
|
||||
- Example: CLIs distributed via npm or as binaries
|
||||
|
||||
### Skip it for:
|
||||
|
||||
- ❌ **Small scripts**
|
||||
- ❌ **Code that runs once**
|
||||
- ❌ **Development builds**
|
||||
- ❌ **Size-constrained environments**
|
||||
- ❌ **Code with top-level await** (not supported)
|
||||
|
||||
## Limitations
|
||||
|
||||
### CommonJS only
|
||||
|
||||
Bytecode caching currently works with CommonJS output format. Bun's bundler automatically converts most ESM code to CommonJS, but **top-level await** is the exception:
|
||||
|
||||
```js
|
||||
// This prevents bytecode caching
|
||||
const data = await fetch("https://api.example.com");
|
||||
export default data;
|
||||
```
|
||||
|
||||
**Why**: Top-level await requires async module evaluation, which can't be represented in CommonJS. The module graph becomes asynchronous, and the CommonJS wrapper function model breaks down.
|
||||
|
||||
**Workaround**: Move async initialization into a function:
|
||||
|
||||
```js
|
||||
async function init() {
|
||||
const data = await fetch("https://api.example.com");
|
||||
return data;
|
||||
}
|
||||
|
||||
export default init;
|
||||
```
|
||||
|
||||
Now the module exports a function that the consumer can await when needed.
|
||||
|
||||
### Version compatibility
|
||||
|
||||
Bytecode is **not portable across Bun versions**. The bytecode format is tied to JavaScriptCore's internal representation, which changes between versions.
|
||||
|
||||
When you update Bun, you must regenerate bytecode:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
# After updating Bun
|
||||
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 - you just lose the performance optimization.
|
||||
|
||||
**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
|
||||
|
||||
- The `.js` file (your bundled source code)
|
||||
- The `.jsc` file (the bytecode cache)
|
||||
|
||||
At runtime:
|
||||
|
||||
1. Bun loads the `.js` file, sees a `@bytecode` pragma, and checks the `.jsc` file
|
||||
2. Bun loads the `.jsc` file
|
||||
3. Bun validates the bytecode hash matches the source
|
||||
4. If valid, Bun uses the bytecode
|
||||
5. If invalid, Bun falls back to parsing the source
|
||||
|
||||
### Bytecode is not obfuscation
|
||||
|
||||
Bytecode **does not obscure your source code**. It's an optimization, not a security measure.
|
||||
|
||||
## Production deployment
|
||||
|
||||
### Docker
|
||||
|
||||
Include bytecode generation in your Dockerfile:
|
||||
|
||||
```dockerfile Dockerfile icon="docker"
|
||||
FROM oven/bun:1 AS builder
|
||||
WORKDIR /app
|
||||
COPY package.json bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
RUN bun build --bytecode --minify --sourcemap \
|
||||
--target=bun \
|
||||
--outdir=./dist \
|
||||
--compile \
|
||||
./src/server.ts --outfile=./dist/server
|
||||
|
||||
FROM oven/bun:1 AS runner
|
||||
WORKDIR /app
|
||||
COPY --from=builder /dist/server /app/server
|
||||
CMD ["./server"]
|
||||
```
|
||||
|
||||
The bytecode is architecture-independent.
|
||||
|
||||
### CI/CD
|
||||
|
||||
Generate bytecode during your build pipeline:
|
||||
|
||||
```yaml workflow.yml icon="file-code"
|
||||
# GitHub Actions
|
||||
- name: Build with bytecode
|
||||
run: |
|
||||
bun install
|
||||
bun build --bytecode --minify \
|
||||
--outdir=./dist \
|
||||
--target=bun \
|
||||
./src/index.ts
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
### Verify bytecode is being used
|
||||
|
||||
Check that the `.jsc` file exists:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
ls -lh dist/
|
||||
```
|
||||
|
||||
```txt
|
||||
-rw-r--r-- 1 user staff 245K index.js
|
||||
-rw-r--r-- 1 user staff 1.1M index.jsc
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
On success, it will log something like:
|
||||
|
||||
```txt
|
||||
[Disk cache] cache hit for sourceCode
|
||||
```
|
||||
|
||||
If you see a cache miss, it will log something like:
|
||||
|
||||
```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.
|
||||
|
||||
### Common issues
|
||||
|
||||
**Bytecode silently ignored**: Usually caused by a Bun version update. The cache version doesn't match, so bytecode is rejected. Regenerate to fix.
|
||||
|
||||
**File size too large**: This is expected. Consider:
|
||||
|
||||
- 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
|
||||
|
||||
**Top-level await**: Not supported. Refactor to use async initialization functions.
|
||||
|
||||
## What is bytecode?
|
||||
|
||||
When you run JavaScript, the JavaScript engine doesn't execute your source code directly. Instead, it goes through several steps:
|
||||
|
||||
1. **Parsing**: The engine reads your JavaScript source code and converts it into an Abstract Syntax Tree (AST)
|
||||
2. **Bytecode compilation**: The AST is compiled into bytecode - a lower-level representation that's faster to execute
|
||||
3. **Execution**: The bytecode is executed by the engine's interpreter or JIT compiler
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
// Without bytecode caching:
|
||||
function rarely_used() {
|
||||
// This 500-line function is only parsed
|
||||
// when it's actually called
|
||||
}
|
||||
|
||||
function main() {
|
||||
console.log("Starting app");
|
||||
// rarely_used() is never called, so it's never parsed
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
**Header section** (validated on every load):
|
||||
|
||||
- **Cache version**: A hash tied to the JavaScriptCore framework version. This ensures bytecode generated with one version of Bun only runs with that exact version.
|
||||
- **Code block type tag**: Identifies whether this is a Program, Module, Eval, or Function code block.
|
||||
|
||||
**SourceCodeKey** (validates bytecode matches source):
|
||||
|
||||
- **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.
|
||||
|
||||
**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).
|
||||
- **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.
|
||||
- **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.).
|
||||
|
||||
**Function metadata** (for each function in your code):
|
||||
|
||||
- **Register allocation**: How many registers (local variables) the function needs - `thisRegister`, `scopeRegister`, `numVars`, `numCalleeLocals`, `numParameters`.
|
||||
- **Code features**: A bitmask of function characteristics: is it a constructor? an arrow function? does it use `super`? does it have tail calls? These affect how the function is executed.
|
||||
- **Lexically scoped features**: Strict mode and other lexical context.
|
||||
- **Parse mode**: The mode in which the function was parsed (normal, async, generator, async generator).
|
||||
|
||||
**Nested structures**:
|
||||
|
||||
- **Function declarations and expressions**: Each nested function gets its own bytecode block, recursively. A file with 100 functions has 100 separate bytecode blocks, all nested in the structure.
|
||||
- **Exception handlers**: Try/catch/finally blocks with their boundaries and handler addresses pre-computed.
|
||||
- **Expression info**: Maps bytecode positions back to source code locations for error reporting and debugging.
|
||||
|
||||
### What bytecode does NOT contain
|
||||
|
||||
Importantly, **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.
|
||||
|
||||
## The tradeoff: file size
|
||||
|
||||
Bytecode files are significantly larger than source code - typically 2-8x larger.
|
||||
|
||||
### Why is bytecode so much larger?
|
||||
|
||||
**Bytecode instructions are verbose**:
|
||||
A single line of minified JavaScript might compile to dozens of bytecode instructions. For example:
|
||||
|
||||
```js
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
```
|
||||
|
||||
Compiles to bytecode that:
|
||||
|
||||
- Loads the `arr` variable
|
||||
- Gets the `reduce` property
|
||||
- Creates the arrow function (which itself has bytecode)
|
||||
- Loads the initial value `0`
|
||||
- Sets up the call with the right number of arguments
|
||||
- Actually performs the call
|
||||
- Stores the result in `sum`
|
||||
|
||||
Each of these steps is a separate bytecode instruction with its own metadata.
|
||||
|
||||
**Constant pools store everything**:
|
||||
Every string literal, number, property name - everything gets stored in the constant pool. Even if your source code has `"hello"` a hundred times, the constant pool stores it once, but the identifier table and constant references add overhead.
|
||||
|
||||
**Per-function metadata**:
|
||||
Each function - even small one-line functions - gets its own complete metadata:
|
||||
|
||||
- Register allocation info
|
||||
- Code features bitmask
|
||||
- Parse mode
|
||||
- Exception handlers
|
||||
- Expression info for debugging
|
||||
|
||||
A file with 1,000 small functions has 1,000 sets of metadata.
|
||||
|
||||
**Profiling data structures**:
|
||||
Even though profiling data isn't populated yet, the _structures_ to hold profiling data are allocated. This includes:
|
||||
|
||||
- Value profile slots (tracking what types flow through each operation)
|
||||
- Array profile slots (tracking array access patterns)
|
||||
- Binary arithmetic profile slots (tracking number types in math operations)
|
||||
- Unary arithmetic profile slots
|
||||
|
||||
These take up space even when empty.
|
||||
|
||||
**Pre-computed control flow**:
|
||||
Jump targets, switch tables, and exception handler boundaries are all pre-computed and stored. This makes execution faster but increases file size.
|
||||
|
||||
### Mitigation strategies
|
||||
|
||||
**Compression**:
|
||||
Bytecode compresses extremely well with gzip/brotli (60-70% compression). The repetitive structure and metadata compress efficiently.
|
||||
|
||||
**Minification first**:
|
||||
Using `--minify` before bytecode generation helps:
|
||||
|
||||
- Shorter identifiers → smaller identifier table
|
||||
- Dead code elimination → less bytecode generated
|
||||
- Constant folding → fewer constants in the pool
|
||||
|
||||
**The tradeoff**:
|
||||
You're trading 2-4x larger files for 2-4x faster startup. For CLIs, this is usually worth it. For long-running servers where a few megabytes of disk space don't matter, it's even less of an issue.
|
||||
|
||||
## Versioning and portability
|
||||
|
||||
### Cross-architecture portability: ✅
|
||||
|
||||
Bytecode is **architecture-independent**. You can:
|
||||
|
||||
- Build on macOS ARM64, deploy to Linux x64
|
||||
- Build on Linux x64, deploy to AWS Lambda ARM64
|
||||
- Build on Windows x64, deploy to macOS ARM64
|
||||
|
||||
The bytecode contains abstract instructions that work on any architecture. Architecture-specific optimizations happen during JIT compilation at runtime, not in the cached bytecode.
|
||||
|
||||
### Cross-version portability: ❌
|
||||
|
||||
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.
|
||||
|
||||
**Version validation**:
|
||||
The cache version in the `.jsc` file header is a hash of the JavaScriptCore framework. When Bun loads bytecode:
|
||||
|
||||
1. It extracts the cache version from the `.jsc` file
|
||||
2. It computes the current JavaScriptCore version
|
||||
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 - you just lose the performance optimization.
|
||||
|
||||
**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:
|
||||
|
||||
### Unlinked bytecode (what's cached)
|
||||
|
||||
The bytecode saved in `.jsc` files is **unlinked bytecode**. It contains:
|
||||
|
||||
- The compiled bytecode instructions
|
||||
- Structural information about the code
|
||||
- Constants and identifiers
|
||||
- Control flow information
|
||||
|
||||
But it **doesn't** contain:
|
||||
|
||||
- Pointers to actual runtime objects
|
||||
- JIT-compiled machine code
|
||||
- Profiling data from previous runs
|
||||
- Call link information (which functions call which)
|
||||
|
||||
Unlinked bytecode is **immutable and shareable**. Multiple executions of the same code can all reference the same unlinked bytecode.
|
||||
|
||||
### Linked bytecode (runtime execution)
|
||||
|
||||
When Bun runs bytecode, it "links" it - creating a runtime wrapper that adds:
|
||||
|
||||
- **Call link information**: As your code runs, the engine learns which functions call which and optimizes those call sites.
|
||||
- **Profiling data**: The engine tracks how many times each instruction executes, what types of values flow through the code, array access patterns, etc.
|
||||
- **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:
|
||||
|
||||
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.
|
||||
@@ -1,3 +1,8 @@
|
||||
---
|
||||
title: CSS
|
||||
description: Bun's bundler has built-in support for CSS with modern features
|
||||
---
|
||||
|
||||
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)
|
||||
@@ -9,11 +14,11 @@ Bun's bundler has built-in support for CSS with the following features:
|
||||
|
||||
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.
|
||||
|
||||
Bun's CSS parser and bundler is a direct Rust → Zig port of [LightningCSS](https://lightningcss.dev/), with a bundling approach inspired by esbuild. The transpiler converts modern CSS syntax into backwards-compatible equivalents that work across browsers.
|
||||
Bun's CSS parser and bundler is a direct Rust → Zig 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](https://lightningcss.dev/) and [esbuild](https://esbuild.github.io/).
|
||||
<Note>A huge thanks goes to the amazing work from the authors of LightningCSS and esbuild.</Note>
|
||||
|
||||
### Browser Compatibility
|
||||
## Browser Compatibility
|
||||
|
||||
By default, Bun's CSS bundler targets the following browsers:
|
||||
|
||||
@@ -23,13 +28,13 @@ By default, Bun's CSS bundler targets the following browsers:
|
||||
- Chrome 87+
|
||||
- Safari 14+
|
||||
|
||||
### Syntax Lowering
|
||||
## Syntax Lowering
|
||||
|
||||
#### Nesting
|
||||
### 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* With nesting */
|
||||
.card {
|
||||
background: white;
|
||||
@@ -48,7 +53,7 @@ The CSS Nesting specification allows you to write more concise and intuitive sty
|
||||
|
||||
Bun's CSS bundler automatically converts this nested syntax into traditional flat CSS that works in all browsers:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Compiled output */
|
||||
.card {
|
||||
background: white;
|
||||
@@ -67,7 +72,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.responsive-element {
|
||||
display: block;
|
||||
|
||||
@@ -79,7 +84,7 @@ You can also nest media queries and other at-rules inside selectors, eliminating
|
||||
|
||||
This compiles to:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.responsive-element {
|
||||
display: block;
|
||||
}
|
||||
@@ -91,11 +96,11 @@ This compiles to:
|
||||
}
|
||||
```
|
||||
|
||||
#### Color mix
|
||||
### Color mix
|
||||
|
||||
The `color-mix()` function gives you an easy way to blend two colors together according to a specified ratio in a chosen color space. This powerful feature lets you create color variations without manually calculating the resulting values.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.button {
|
||||
/* Mix blue and red in the RGB color space with a 30/70 proportion */
|
||||
background-color: color-mix(in srgb, blue 30%, red);
|
||||
@@ -109,7 +114,7 @@ The `color-mix()` function gives you an easy way to blend two colors together ac
|
||||
|
||||
Bun's CSS bundler evaluates these color mixes at build time when all color values are known (not CSS variables), generating static color values that work in all browsers:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.button {
|
||||
/* Computed to the exact resulting color */
|
||||
background-color: #b31a1a;
|
||||
@@ -122,11 +127,11 @@ 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
|
||||
### Relative colors
|
||||
|
||||
CSS now allows you to modify individual components of a color using relative color syntax. This powerful feature lets you create color variations by adjusting specific attributes like lightness, saturation, or individual channels without having to recalculate the entire color.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.theme-color {
|
||||
/* Start with a base color and increase lightness by 15% */
|
||||
--accent: lch(from purple calc(l + 15%) c h);
|
||||
@@ -147,27 +152,23 @@ 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.
|
||||
|
||||
#### LAB colors
|
||||
### 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.vibrant-element {
|
||||
/* A vibrant red that exceeds sRGB gamut boundaries */
|
||||
color: lab(55% 78 35);
|
||||
|
||||
/* A smooth gradient using perceptual color space */
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
oklch(65% 0.25 10deg),
|
||||
oklch(65% 0.25 250deg)
|
||||
);
|
||||
background: linear-gradient(to right, oklch(65% 0.25 10deg), oklch(65% 0.25 250deg));
|
||||
}
|
||||
```
|
||||
|
||||
Bun's CSS bundler automatically converts these advanced color formats to backwards-compatible alternatives for browsers that don't yet support them:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.vibrant-element {
|
||||
/* Fallback to closest RGB approximation */
|
||||
color: #ff0f52;
|
||||
@@ -177,21 +178,17 @@ Bun's CSS bundler automatically converts these advanced color formats to backwar
|
||||
color: lab(55% 78 35);
|
||||
|
||||
background: linear-gradient(to right, #cd4e15, #3887ab);
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
oklch(65% 0.25 10deg),
|
||||
oklch(65% 0.25 250deg)
|
||||
);
|
||||
background: linear-gradient(to right, oklch(65% 0.25 10deg), oklch(65% 0.25 250deg));
|
||||
}
|
||||
```
|
||||
|
||||
This layered approach ensures optimal color rendering across all browsers while allowing you to use the latest color technologies in your designs.
|
||||
|
||||
#### Color function
|
||||
### 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.vivid-element {
|
||||
/* Using the Display P3 color space for wider gamut colors */
|
||||
color: color(display-p3 1 0.1 0.3);
|
||||
@@ -203,7 +200,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.vivid-element {
|
||||
/* RGB fallback first for maximum compatibility */
|
||||
color: #fa1a4c;
|
||||
@@ -217,11 +214,11 @@ 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
|
||||
### HWB colors
|
||||
|
||||
The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to express 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.easy-theming {
|
||||
/* Pure cyan with no white or black added */
|
||||
--primary: hwb(180 0% 0%);
|
||||
@@ -239,7 +236,7 @@ The HWB (Hue, Whiteness, Blackness) color model provides an intuitive way to exp
|
||||
|
||||
Bun's CSS bundler automatically converts HWB colors to RGB for compatibility with all browsers:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.easy-theming {
|
||||
--primary: #00ffff;
|
||||
--primary-light: #33ffff;
|
||||
@@ -250,11 +247,11 @@ Bun's CSS bundler automatically converts HWB colors to RGB for compatibility wit
|
||||
|
||||
The HWB model makes it particularly easy to create systematic color variations for design systems, providing a more intuitive approach to creating consistent tints and shades than working directly with RGB or HSL values.
|
||||
|
||||
#### Color notation
|
||||
### Color notation
|
||||
|
||||
Modern CSS has introduced more intuitive and 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.modern-styling {
|
||||
/* Space-separated RGB notation (no commas) */
|
||||
color: rgb(50 100 200);
|
||||
@@ -272,7 +269,7 @@ Modern CSS has introduced more intuitive and concise ways to express colors. Spa
|
||||
|
||||
Bun's CSS bundler automatically converts these modern color formats to ensure compatibility with older browsers:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.modern-styling {
|
||||
/* Converted to comma format for older browsers */
|
||||
color: rgb(50, 100, 200);
|
||||
@@ -289,11 +286,11 @@ 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
|
||||
### light-dark() color function
|
||||
|
||||
The `light-dark()` function provides an elegant solution for implementing color schemes that respect the user's system preference without requiring complex media queries. This function accepts two color values and automatically selects the appropriate one based on the current color scheme context.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
:root {
|
||||
/* Define color scheme support */
|
||||
color-scheme: light dark;
|
||||
@@ -318,7 +315,7 @@ The `light-dark()` function provides an elegant solution for implementing color
|
||||
|
||||
For browsers that don't support this feature yet, Bun's CSS bundler converts it to use CSS variables with proper fallbacks:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
:root {
|
||||
--lightningcss-light: initial;
|
||||
--lightningcss-dark: ;
|
||||
@@ -345,21 +342,19 @@ For browsers that don't support this feature yet, Bun's CSS bundler converts it
|
||||
}
|
||||
|
||||
.themed-component {
|
||||
background-color: var(--lightningcss-light, #ffffff)
|
||||
var(--lightningcss-dark, #121212);
|
||||
background-color: var(--lightningcss-light, #ffffff) var(--lightningcss-dark, #121212);
|
||||
color: var(--lightningcss-light, #333333) var(--lightningcss-dark, #eeeeee);
|
||||
border-color: var(--lightningcss-light, #dddddd)
|
||||
var(--lightningcss-dark, #555555);
|
||||
border-color: var(--lightningcss-light, #dddddd) var(--lightningcss-dark, #555555);
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
### 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
|
||||
```css title="styles.css" icon="file-code"
|
||||
.multilingual-component {
|
||||
/* Margin that adapts to writing direction */
|
||||
margin-inline-start: 1rem;
|
||||
@@ -378,7 +373,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* For left-to-right languages */
|
||||
.multilingual-component:dir(ltr) {
|
||||
margin-left: 1rem;
|
||||
@@ -402,11 +397,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.
|
||||
|
||||
#### :dir() selector
|
||||
### :dir() selector
|
||||
|
||||
The `:dir()` pseudo-class selector allows you to style elements based on their text direction (RTL or LTR), providing a powerful way to create direction-aware designs without JavaScript. This selector matches elements based on their directionality as determined by the document or explicit direction attributes.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Apply different styles based on text direction */
|
||||
.nav-arrow:dir(ltr) {
|
||||
transform: rotate(0deg);
|
||||
@@ -428,7 +423,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Converted to use language-based selectors as fallback */
|
||||
.nav-arrow:lang(en, fr, de, es, it, pt, nl) {
|
||||
transform: rotate(0deg);
|
||||
@@ -449,11 +444,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.
|
||||
|
||||
#### :lang() selector
|
||||
### :lang() selector
|
||||
|
||||
The `:lang()` pseudo-class selector allows you to target elements based on the language they're in, making it easy to apply language-specific styling. Modern CSS allows the `:lang()` selector to accept multiple language codes, letting you group language-specific rules more efficiently.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Typography adjustments for CJK languages */
|
||||
:lang(zh, ja, ko) {
|
||||
line-height: 1.8;
|
||||
@@ -472,7 +467,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Multiple languages grouped with :is() for better browser support */
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) {
|
||||
line-height: 1.8;
|
||||
@@ -490,11 +485,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.
|
||||
|
||||
#### :is() selector
|
||||
### :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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Instead of writing these separately */
|
||||
/*
|
||||
.article h1,
|
||||
@@ -547,13 +542,17 @@ For browsers that don't support `:is()`, Bun's CSS bundler provides fallbacks us
|
||||
}
|
||||
```
|
||||
|
||||
It's worth noting that 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.
|
||||
<Warning>
|
||||
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.
|
||||
</Warning>
|
||||
|
||||
#### :not() selector
|
||||
### :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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Select all buttons except primary and secondary variants */
|
||||
button:not(.primary, .secondary) {
|
||||
background-color: #f5f5f5;
|
||||
@@ -568,7 +567,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Converted to use :not with :is() for compatibility */
|
||||
button:not(:is(.primary, .secondary)) {
|
||||
background-color: #f5f5f5;
|
||||
@@ -582,7 +581,7 @@ h2:not(:is(.sidebar *, footer *)) {
|
||||
|
||||
And if `:is()` isn't supported, Bun can generate further fallbacks:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Even more fallbacks for maximum compatibility */
|
||||
button:not(:-webkit-any(.primary, .secondary)) {
|
||||
background-color: #f5f5f5;
|
||||
@@ -602,11 +601,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.
|
||||
|
||||
#### Math functions
|
||||
### 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
|
||||
```css title="styles.css" icon="file-code"
|
||||
.dynamic-sizing {
|
||||
/* Clamp a value between minimum and maximum */
|
||||
width: clamp(200px, 50%, 800px);
|
||||
@@ -625,7 +624,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.dynamic-sizing {
|
||||
width: clamp(200px, 50%, 800px);
|
||||
padding: 15px;
|
||||
@@ -637,11 +636,11 @@ 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
|
||||
### Media query ranges
|
||||
|
||||
Modern CSS supports intuitive 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 we normally think about values and ranges.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Modern syntax with comparison operators */
|
||||
@media (width >= 768px) {
|
||||
.container {
|
||||
@@ -666,7 +665,7 @@ Modern CSS supports intuitive range syntax for media queries, allowing you to sp
|
||||
|
||||
Bun's CSS bundler converts these modern range queries to traditional media query syntax for compatibility with all browsers:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Converted to traditional min/max syntax */
|
||||
@media (min-width: 768px) {
|
||||
.container {
|
||||
@@ -689,11 +688,11 @@ Bun's CSS bundler converts these modern range queries to traditional media query
|
||||
|
||||
This lets you write more intuitive and mathematical media queries while ensuring your stylesheets work correctly across all browsers, including those that don't support the modern range syntax.
|
||||
|
||||
#### Shorthands
|
||||
### 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
|
||||
```css title="styles.css" icon="file-code"
|
||||
/* Alignment shorthands */
|
||||
.flex-container {
|
||||
/* Shorthand for align-items and justify-items */
|
||||
@@ -729,7 +728,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.flex-container {
|
||||
/* Expanded alignment properties */
|
||||
align-items: center;
|
||||
@@ -766,11 +765,11 @@ 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
|
||||
### 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.striped-background {
|
||||
/* Creates a sharp transition from green to red at 30%-40% */
|
||||
background: linear-gradient(
|
||||
@@ -799,7 +798,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.striped-background {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
@@ -830,11 +829,11 @@ 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
|
||||
### 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.
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.native-interface {
|
||||
/* Use the system's default UI font */
|
||||
font-family: system-ui;
|
||||
@@ -848,7 +847,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:
|
||||
|
||||
```css
|
||||
```css title="styles.css" icon="file-code"
|
||||
.native-interface {
|
||||
/* Expanded to support all major platforms */
|
||||
font-family:
|
||||
@@ -883,7 +882,7 @@ This approach gives you the simplicity of writing just `system-ui` in your sourc
|
||||
|
||||
## CSS Modules
|
||||
|
||||
Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
|
||||
Bun's bundler also supports bundling CSS modules in addition to regular CSS with support for the following features:
|
||||
|
||||
- Automatically detecting CSS module files (`.module.css`) with zero configuration
|
||||
- Composition (`composes` property)
|
||||
@@ -894,17 +893,17 @@ A CSS module is a CSS file (with the `.module.css` extension) where are all clas
|
||||
|
||||
Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
|
||||
|
||||
## Getting started
|
||||
### Getting started
|
||||
|
||||
Create a CSS file with the `.module.css` extension:
|
||||
|
||||
```css
|
||||
/* styles.module.css */
|
||||
```css title="styles.module.css" icon="file-code"
|
||||
.button {
|
||||
color: red;
|
||||
}
|
||||
```
|
||||
|
||||
/* other-styles.module.css */
|
||||
```css title="other-styles.module.css" icon="file-code"
|
||||
.button {
|
||||
color: blue;
|
||||
}
|
||||
@@ -912,7 +911,7 @@ Create a CSS file with the `.module.css` extension:
|
||||
|
||||
You can then import this file, for example into a TSX file:
|
||||
|
||||
```tsx
|
||||
```tsx title="app.tsx" icon="/icons/typescript.svg"
|
||||
import styles from "./styles.module.css";
|
||||
import otherStyles from "./other-styles.module.css";
|
||||
|
||||
@@ -926,10 +925,9 @@ 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:
|
||||
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:
|
||||
|
||||
```tsx
|
||||
```ts title="app.tsx" icon="/icons/typescript.svg"
|
||||
import styles from "./styles.module.css";
|
||||
import otherStyles from "./other-styles.module.css";
|
||||
|
||||
@@ -939,7 +937,7 @@ console.log(otherStyles);
|
||||
|
||||
This will output:
|
||||
|
||||
```ts
|
||||
```ts title="app.tsx" icon="/icons/typescript.svg"
|
||||
{
|
||||
button: "button_123";
|
||||
}
|
||||
@@ -953,12 +951,11 @@ As you can see, the class names are unique to each file, avoiding any collisions
|
||||
|
||||
### Composition
|
||||
|
||||
CSS modules allow you to _compose_ class selectors together. This lets you reuse style rules across multiple classes.
|
||||
CSS modules allow you to compose class selectors together. This lets you reuse style rules across multiple classes.
|
||||
|
||||
For example:
|
||||
|
||||
```css
|
||||
/* styles.module.css */
|
||||
```css title="styles.module.css" icon="file-code"
|
||||
.button {
|
||||
composes: background;
|
||||
color: red;
|
||||
@@ -971,7 +968,7 @@ For example:
|
||||
|
||||
Would be the same as writing:
|
||||
|
||||
```css
|
||||
```css title="styles.module.css" icon="file-code"
|
||||
.button {
|
||||
background-color: blue;
|
||||
color: red;
|
||||
@@ -982,13 +979,14 @@ Would be the same as writing:
|
||||
}
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
There are a couple rules to keep in mind when using `composes`:
|
||||
|
||||
- A `composes` property must come before any regular CSS properties or declarations
|
||||
- You can only use `composes` on a **simple selector with a single class name**:
|
||||
<Info>
|
||||
**Composition Rules:** - A `composes` property must come before any regular CSS properties or declarations - You can
|
||||
only use `composes` on a simple selector with a single class name
|
||||
</Info>
|
||||
|
||||
```css
|
||||
```css title="styles.module.css" icon="file-code"
|
||||
#button {
|
||||
/* Invalid! `#button` is not a class selector */
|
||||
composes: background;
|
||||
@@ -1001,28 +999,26 @@ There are a couple rules to keep in mind when using `composes`:
|
||||
}
|
||||
```
|
||||
|
||||
{% /callout %}
|
||||
|
||||
### Composing from a separate CSS module file
|
||||
|
||||
You can also compose from a separate CSS module file:
|
||||
|
||||
```css
|
||||
/* background.module.css */
|
||||
```css title="background.module.css" icon="file-code"
|
||||
.background {
|
||||
background-color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
/* styles.module.css */
|
||||
```css title="styles.module.css" icon="file-code"
|
||||
.button {
|
||||
composes: background from "./background.module.css";
|
||||
color: red;
|
||||
}
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
<Warning>
|
||||
When composing classes from separate files, be sure that 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.
|
||||
{% /callout %}
|
||||
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.
|
||||
|
||||
</Warning>
|
||||
@@ -1,145 +0,0 @@
|
||||
# CSS Modules
|
||||
|
||||
Bun's bundler also supports bundling [CSS modules](https://css-tricks.com/css-modules-part-1-need/) in addition to [regular CSS](/docs/bundler/css) with support for the following features:
|
||||
|
||||
- Automatically detecting CSS module files (`.module.css`) with zero 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.
|
||||
|
||||
Under the hood, Bun's bundler transforms locally scoped class names into unique identifiers.
|
||||
|
||||
## Getting started
|
||||
|
||||
Create a CSS file with the `.module.css` extension:
|
||||
|
||||
```css
|
||||
/* styles.module.css */
|
||||
.button {
|
||||
color: red;
|
||||
}
|
||||
|
||||
/* other-styles.module.css */
|
||||
.button {
|
||||
color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
You can then import this file, for example into a TSX file:
|
||||
|
||||
```tsx
|
||||
import styles from "./styles.module.css";
|
||||
import otherStyles from "./other-styles.module.css";
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<>
|
||||
<button className={styles.button}>Red button!</button>
|
||||
<button className={otherStyles.button}>Blue button!</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```tsx
|
||||
import styles from "./styles.module.css";
|
||||
import otherStyles from "./other-styles.module.css";
|
||||
|
||||
console.log(styles);
|
||||
console.log(otherStyles);
|
||||
```
|
||||
|
||||
This will output:
|
||||
|
||||
```ts
|
||||
{
|
||||
button: "button_123";
|
||||
}
|
||||
|
||||
{
|
||||
button: "button_456";
|
||||
}
|
||||
```
|
||||
|
||||
As you can see, the class names are unique to each file, avoiding any collisions!
|
||||
|
||||
### Composition
|
||||
|
||||
CSS modules allow you to _compose_ class selectors together. This lets you reuse style rules across multiple classes.
|
||||
|
||||
For example:
|
||||
|
||||
```css
|
||||
/* styles.module.css */
|
||||
.button {
|
||||
composes: background;
|
||||
color: red;
|
||||
}
|
||||
|
||||
.background {
|
||||
background-color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
Would be the same as writing:
|
||||
|
||||
```css
|
||||
.button {
|
||||
background-color: blue;
|
||||
color: red;
|
||||
}
|
||||
|
||||
.background {
|
||||
background-color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
There are a couple rules to keep in mind when using `composes`:
|
||||
|
||||
- A `composes` property must come before any regular CSS properties or declarations
|
||||
- You can only use `composes` on a **simple selector with a single class name**:
|
||||
|
||||
```css
|
||||
#button {
|
||||
/* Invalid! `#button` is not a class selector */
|
||||
composes: background;
|
||||
}
|
||||
|
||||
.button,
|
||||
.button-secondary {
|
||||
/* Invalid! `.button, .button-secondary` is not a simple selector */
|
||||
composes: background;
|
||||
}
|
||||
```
|
||||
|
||||
{% /callout %}
|
||||
|
||||
### Composing from a separate CSS module file
|
||||
|
||||
You can also compose from a separate CSS module file:
|
||||
|
||||
```css
|
||||
/* background.module.css */
|
||||
.background {
|
||||
background-color: blue;
|
||||
}
|
||||
|
||||
/* styles.module.css */
|
||||
.button {
|
||||
composes: background from "./background.module.css";
|
||||
color: red;
|
||||
}
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
When composing classes from separate files, be sure that 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.
|
||||
{% /callout %}
|
||||
253
docs/bundler/esbuild.mdx
Normal file
253
docs/bundler/esbuild.mdx
Normal file
@@ -0,0 +1,253 @@
|
||||
---
|
||||
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.
|
||||
|
||||
There are a few behavioral differences to note.
|
||||
|
||||
<Note>
|
||||
**Bundling by default.** Unlike esbuild, Bun always bundles by default. This is why the `--bundle` flag isn't
|
||||
necessary in the Bun example. To transpile each file individually, use `Bun.Transpiler`.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
**It's just a bundler.** Unlike esbuild, Bun's bundler does not include a built-in development server or file watcher.
|
||||
It's just a bundler. The bundler is intended for use in conjunction with `Bun.serve` and other runtime APIs to achieve
|
||||
the same effect. As such, all options relating to HTTP/file watching are not applicable.
|
||||
</Note>
|
||||
|
||||
## Performance
|
||||
|
||||
With a performance-minded API coupled with the extensively optimized Zig-based JS/TS parser, Bun's bundler is 1.75x faster than esbuild on esbuild's three.js benchmark.
|
||||
|
||||
<Info>Bundling 10 copies of three.js from scratch, with sourcemaps and minification</Info>
|
||||
|
||||
## CLI API
|
||||
|
||||
Bun and esbuild both provide a command-line interface.
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
# esbuild
|
||||
esbuild <entrypoint> --outdir=out --bundle
|
||||
|
||||
# bun
|
||||
bun build <entrypoint> --outdir=out
|
||||
```
|
||||
|
||||
In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Other flags like `--outdir <path>` do accept an argument; these flags can be written as `--outdir out` or `--outdir=out`. Some flags like `--define` can be specified several times: `--define foo=bar --define bar=baz`.
|
||||
|
||||
| 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.<br/>`esbuild --define:foo=bar`<br/>`bun build --define foo=bar` |
|
||||
| `--external:<pkg>` | `--external <pkg>` | Small syntax difference; no colon.<br/>`esbuild --external:react`<br/>`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.<br/><br/>The syntax for `--loader` is slightly different.<br/>`esbuild app.ts --bundle --loader:.svg=text`<br/>`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` | |
|
||||
| `--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 <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. |
|
||||
|
||||
## 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.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> naming: {<br/> asset: "[name].[ext]",<br/> },<br/>});<br/>` |
|
||||
| `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.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> naming: {<br/> chunk: "[name].[ext]",<br/> },<br/>});<br/>` |
|
||||
| `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.<br/><br/>`ts<br/>Bun.build({<br/> entrypoints: ["./index.tsx"],<br/> // when string, this is equivalent to entryNames<br/> naming: "[name].[ext]",<br/><br/> // granular naming options<br/> naming: {<br/> entry: "[name].[ext]",<br/> asset: "[name].[ext]",<br/> chunk: "[name].[ext]",<br/> },<br/>});<br/>` |
|
||||
| `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.<br/><br/>`ts<br/>await Bun.build({<br/> entrypoints: ['./index.tsx'],<br/> // enable all minification<br/> minify: true<br/><br/> // granular options<br/> minify: {<br/> identifiers: true,<br/> syntax: true,<br/> whitespace: true<br/> }<br/>})<br/>` |
|
||||
| `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 |
|
||||
|
||||
## 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.
|
||||
|
||||
<Note>
|
||||
Long term, we aim for feature parity with esbuild's API, so if something doesn't work please file an issue to help us
|
||||
prioritize.
|
||||
</Note>
|
||||
|
||||
Plugins in Bun and esbuild are defined with a builder object.
|
||||
|
||||
```ts title="myPlugin.ts" icon="/icons/typescript.svg"
|
||||
import type { BunPlugin } from "bun";
|
||||
|
||||
const myPlugin: BunPlugin = {
|
||||
name: "my-plugin",
|
||||
setup(builder) {
|
||||
// define plugin
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
The builder object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use `config` (same thing but with Bun's `BuildConfig` format) instead.
|
||||
|
||||
```ts title="myPlugin.ts" icon="/icons/typescript.svg"
|
||||
import type { BunPlugin } from "bun";
|
||||
const myPlugin: BunPlugin = {
|
||||
name: "my-plugin",
|
||||
setup(builder) {
|
||||
builder.onResolve(
|
||||
{
|
||||
/* onResolve.options */
|
||||
},
|
||||
args => {
|
||||
return {
|
||||
/* onResolve.results */
|
||||
};
|
||||
},
|
||||
);
|
||||
builder.onLoad(
|
||||
{
|
||||
/* onLoad.options */
|
||||
},
|
||||
args => {
|
||||
return {
|
||||
/* onLoad.results */
|
||||
};
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### onResolve
|
||||
|
||||
<Tabs>
|
||||
<Tab title="options">- 🟢 `filter` - 🟢 `namespace`</Tab>
|
||||
<Tab title="arguments">
|
||||
- 🟢 `path` - 🟢 `importer` - 🔴 `namespace` - 🔴 `resolveDir` - 🔴 `kind` - 🔴 `pluginData`
|
||||
</Tab>
|
||||
<Tab title="results">
|
||||
- 🟢 `namespace` - 🟢 `path` - 🔴 `errors` - 🔴 `external` - 🔴 `pluginData` - 🔴 `pluginName` - 🔴 `sideEffects` -
|
||||
🔴 `suffix` - 🔴 `warnings` - 🔴 `watchDirs` - 🔴 `watchFiles`
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### onLoad
|
||||
|
||||
<Tabs>
|
||||
<Tab title="options">- 🟢 `filter` - 🟢 `namespace`</Tab>
|
||||
<Tab title="arguments">- 🟢 `path` - 🔴 `namespace` - 🔴 `suffix` - 🔴 `pluginData`</Tab>
|
||||
<Tab title="results">
|
||||
- 🟢 `contents` - 🟢 `loader` - 🔴 `errors` - 🔴 `pluginData` - 🔴 `pluginName` - 🔴 `resolveDir` - 🔴 `warnings` -
|
||||
🔴 `watchDirs` - 🔴 `watchFiles`
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -1,33 +1,43 @@
|
||||
---
|
||||
title: "Single-file executable"
|
||||
description: "Generate standalone executables from TypeScript or JavaScript files with Bun"
|
||||
---
|
||||
|
||||
Bun's bundler implements a `--compile` flag for generating a standalone binary from a TypeScript or JavaScript file.
|
||||
|
||||
{% codetabs %}
|
||||
<CodeGroup>
|
||||
|
||||
```bash
|
||||
$ bun build ./cli.ts --compile --outfile mycli
|
||||
```bash terminal icon="terminal"
|
||||
bun build ./cli.ts --compile --outfile mycli
|
||||
```
|
||||
|
||||
```ts#cli.ts
|
||||
```ts cli.ts icon="/icons/typescript.svg"
|
||||
console.log("Hello world!");
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
</CodeGroup>
|
||||
|
||||
This bundles `cli.ts` into an executable that can be executed directly:
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
./mycli
|
||||
```
|
||||
$ ./mycli
|
||||
|
||||
```txt
|
||||
Hello world!
|
||||
```
|
||||
|
||||
All imported files and packages are bundled into the executable, along with a copy of the Bun runtime. All built-in Bun and Node.js APIs are supported.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
To build for Linux x64 (most servers):
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp
|
||||
|
||||
# To support CPUs from before 2013, use the baseline version (nehalem)
|
||||
@@ -40,14 +50,14 @@ bun build --compile --target=bun-linux-x64-modern ./index.ts --outfile myapp
|
||||
|
||||
To build for Linux ARM64 (e.g. Graviton or Raspberry Pi):
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
# Note: the default architecture is x64 if no architecture is specified.
|
||||
bun build --compile --target=bun-linux-arm64 ./index.ts --outfile myapp
|
||||
```
|
||||
|
||||
To build for Windows x64:
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --target=bun-windows-x64 ./path/to/my/app.ts --outfile myapp
|
||||
|
||||
# To support CPUs from before 2013, use the baseline version (nehalem)
|
||||
@@ -61,17 +71,17 @@ bun build --compile --target=bun-windows-x64-modern ./path/to/my/app.ts --outfil
|
||||
|
||||
To build for macOS arm64:
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --target=bun-darwin-arm64 ./path/to/my/app.ts --outfile myapp
|
||||
```
|
||||
|
||||
To build for macOS x64:
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --target=bun-darwin-x64 ./path/to/my/app.ts --outfile myapp
|
||||
```
|
||||
|
||||
#### Supported targets
|
||||
### Supported targets
|
||||
|
||||
The order of the `--target` flag does not matter, as long as they're delimited by a `-`.
|
||||
|
||||
@@ -86,21 +96,32 @@ The order of the `--target` flag does not matter, as long as they're delimited b
|
||||
| bun-linux-x64-musl | Linux | x64 | ✅ | ✅ | musl |
|
||||
| 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.
|
||||
<Warning>
|
||||
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.
|
||||
</Warning>
|
||||
|
||||
---
|
||||
|
||||
## Build-time constants
|
||||
|
||||
Use the `--define` flag to inject build-time constants into your executable, such as version numbers, build timestamps, or configuration values:
|
||||
|
||||
```bash
|
||||
$ bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --define BUILD_VERSION='"1.2.3"' --define BUILD_TIME='"2024-01-15T10:30:00Z"' src/cli.ts --outfile mycli
|
||||
```
|
||||
|
||||
These constants are embedded directly into your compiled binary at build time, providing zero runtime overhead and enabling dead code elimination optimizations.
|
||||
|
||||
{% callout type="info" %}
|
||||
For comprehensive examples and advanced patterns, see the [Build-time constants guide](/guides/runtime/build-time-constants).
|
||||
{% /callout %}
|
||||
<Note>
|
||||
For comprehensive examples and advanced patterns, see the [Build-time constants
|
||||
guide](https://bun.com/guides/runtime/build-time-constants).
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
## Deploying to production
|
||||
|
||||
@@ -112,7 +133,7 @@ With compiled executables, you can move that cost from runtime to build-time.
|
||||
|
||||
When deploying to production, we recommend the following:
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
|
||||
```
|
||||
|
||||
@@ -120,17 +141,22 @@ bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
|
||||
|
||||
To improve startup time, enable bytecode compilation:
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --minify --sourcemap --bytecode ./path/to/my/app.ts --outfile myapp
|
||||
```
|
||||
|
||||
Using bytecode compilation, `tsc` starts 2x faster:
|
||||
|
||||
{% image src="https://github.com/user-attachments/assets/dc8913db-01d2-48f8-a8ef-ac4e984f9763" width="689" /%}
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Bytecode compilation moves parsing overhead for large input files from runtime to bundle time. Your app starts faster, in exchange for making the `bun build` command a little slower. It doesn't obscure source code.
|
||||
|
||||
**Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is supported (which means no top-level-await). Let us know if you run into any issues!
|
||||
<Warning>
|
||||
**Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is
|
||||
supported (which means no top-level-await). Let us know if you run into any issues!
|
||||
</Warning>
|
||||
|
||||
### What do these flags do?
|
||||
|
||||
@@ -140,68 +166,77 @@ The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that erro
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Embedding runtime arguments
|
||||
|
||||
**`--compile-exec-argv="args"`** - Embed runtime arguments that are available via `process.execArgv`:
|
||||
|
||||
```bash
|
||||
```bash icon="terminal" terminal
|
||||
bun build --compile --compile-exec-argv="--smol --user-agent=MyBot" ./app.ts --outfile myapp
|
||||
```
|
||||
|
||||
```js
|
||||
```ts app.ts icon="/icons/typescript.svg"
|
||||
// In the compiled app
|
||||
console.log(process.execArgv); // ["--smol", "--user-agent=MyBot"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Act as the Bun CLI
|
||||
|
||||
{% note %}
|
||||
|
||||
New in Bun v1.2.16
|
||||
|
||||
{% /note %}
|
||||
<Note>New in Bun v1.2.16</Note>
|
||||
|
||||
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.
|
||||
|
||||
For example, consider an executable compiled from a simple script:
|
||||
|
||||
```sh
|
||||
$ cat such-bun.js
|
||||
console.log("you shouldn't see this");
|
||||
```bash icon="terminal" terminal
|
||||
echo "console.log(\"you shouldn't see this\");" > such-bun.js
|
||||
bun build --compile ./such-bun.js
|
||||
```
|
||||
|
||||
$ bun build --compile ./such-bun.js
|
||||
[3ms] bundle 1 modules
|
||||
```txt
|
||||
[3ms] bundle 1 modules
|
||||
[89ms] compile such-bun
|
||||
```
|
||||
|
||||
Normally, running `./such-bun` with arguments would execute the script. However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
|
||||
Normally, running `./such-bun` with arguments would execute the script.
|
||||
|
||||
```sh
|
||||
```bash icon="terminal" terminal
|
||||
# Executable runs its own entrypoint by default
|
||||
$ ./such-bun install
|
||||
you shouldn't see this
|
||||
./such-bun install
|
||||
```
|
||||
|
||||
```txt
|
||||
you shouldn't see this
|
||||
```
|
||||
|
||||
However, with the `BUN_BE_BUN=1` environment variable, it acts just like the `bun` binary:
|
||||
|
||||
```bash icon="terminal" terminal
|
||||
# With the env var, the executable acts like the `bun` CLI
|
||||
$ BUN_BE_BUN=1 ./such-bun install
|
||||
bun_BE_BUN=1 ./such-bun install
|
||||
```
|
||||
|
||||
```txt
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Full-stack executables
|
||||
|
||||
{% note %}
|
||||
|
||||
New in Bun v1.2.17
|
||||
|
||||
{% /note %}
|
||||
<Note>New in Bun v1.2.17</Note>
|
||||
|
||||
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.
|
||||
|
||||
{% codetabs %}
|
||||
<CodeGroup>
|
||||
|
||||
```ts#server.ts
|
||||
```ts server.ts icon="/icons/typescript.svg"
|
||||
import { serve } from "bun";
|
||||
import index from "./index.html";
|
||||
|
||||
@@ -215,12 +250,12 @@ const server = serve({
|
||||
console.log(`Server running at http://localhost:${server.port}`);
|
||||
```
|
||||
|
||||
```html#index.html
|
||||
```html index.html icon="file-code"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>My App</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
<link rel="stylesheet" href="./styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello World</h1>
|
||||
@@ -229,21 +264,21 @@ console.log(`Server running at http://localhost:${server.port}`);
|
||||
</html>
|
||||
```
|
||||
|
||||
```js#app.js
|
||||
```ts app.js icon="file-code"
|
||||
console.log("Hello from the client!");
|
||||
```
|
||||
|
||||
```css#styles.css
|
||||
```css styles.css icon="file-code"
|
||||
body {
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
</CodeGroup>
|
||||
|
||||
To build this into a single executable:
|
||||
|
||||
```sh
|
||||
```bash terminal icon="terminal"
|
||||
bun build --compile ./server.ts --outfile myapp
|
||||
```
|
||||
|
||||
@@ -256,25 +291,27 @@ This creates a self-contained binary that includes:
|
||||
|
||||
The result is a single file that can be deployed anywhere without needing Node.js, Bun, or any dependencies installed. Just run:
|
||||
|
||||
```sh
|
||||
```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.
|
||||
|
||||
For more details on building full-stack applications with Bun, see the [full-stack guide](/docs/bundler/fullstack).
|
||||
For more details on building full-stack applications with Bun, see the [full-stack guide](/bundler/fullstack).
|
||||
|
||||
---
|
||||
|
||||
## Worker
|
||||
|
||||
To use workers in a standalone executable, add the worker's entrypoint to the CLI arguments:
|
||||
|
||||
```sh
|
||||
$ bun build --compile ./index.ts ./my-worker.ts --outfile myapp
|
||||
```bash terminal icon="terminal"
|
||||
bun build --compile ./index.ts ./my-worker.ts --outfile myapp
|
||||
```
|
||||
|
||||
Then, reference the worker in your code:
|
||||
|
||||
```ts
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
console.log("Hello from Bun!");
|
||||
|
||||
// Any of these will work:
|
||||
@@ -289,13 +326,15 @@ In the future, we may automatically detect usages of statically-known paths in `
|
||||
|
||||
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).
|
||||
|
||||
---
|
||||
|
||||
## SQLite
|
||||
|
||||
You can use `bun:sqlite` imports with `bun build --compile`.
|
||||
|
||||
By default, the database is resolved relative to the current working directory of the process.
|
||||
|
||||
```js
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
import db from "./my.db" with { type: "sqlite" };
|
||||
|
||||
console.log(db.query("select * from users LIMIT 1").get());
|
||||
@@ -303,10 +342,12 @@ 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`.
|
||||
|
||||
```bash terminal icon="terminal"
|
||||
cd /home/me/Desktop
|
||||
./hello
|
||||
```
|
||||
$ cd /home/me/Desktop
|
||||
$ ./hello
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Embed assets & files
|
||||
|
||||
@@ -314,7 +355,7 @@ Standalone executables support embedding files.
|
||||
|
||||
To embed files into an executable with `bun build --compile`, import the file in your code.
|
||||
|
||||
```ts
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
// this becomes an internal file path
|
||||
import icon from "./icon.png" with { type: "file" };
|
||||
import { file } from "bun";
|
||||
@@ -331,7 +372,7 @@ Embedded files can be read using `Bun.file`'s functions or the Node.js `fs.readF
|
||||
|
||||
For example, to read the contents of the embedded file:
|
||||
|
||||
```js
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
import icon from "./icon.png" with { type: "file" };
|
||||
import { file } from "bun";
|
||||
|
||||
@@ -344,7 +385,7 @@ const bytes = await file(icon).arrayBuffer();
|
||||
|
||||
If your application wants to embed a SQLite database, set `type: "sqlite"` in the import attribute and the `embed` attribute to `"true"`.
|
||||
|
||||
```js
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
import myEmbeddedDb from "./my.db" with { type: "sqlite", embed: "true" };
|
||||
|
||||
console.log(myEmbeddedDb.query("select * from users LIMIT 1").get());
|
||||
@@ -356,7 +397,7 @@ This database is read-write, but all changes are lost when the executable exits
|
||||
|
||||
As of Bun v1.0.23, you can embed `.node` files into executables.
|
||||
|
||||
```js
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
const addon = require("./addon.node");
|
||||
|
||||
console.log(addon.hello());
|
||||
@@ -368,13 +409,13 @@ Unfortunately, if you're using `@mapbox/node-pre-gyp` or other similar tools, yo
|
||||
|
||||
To embed a directory with `bun build --compile`, use a shell glob in your `bun build` command:
|
||||
|
||||
```sh
|
||||
$ bun build --compile ./index.ts ./public/**/*.png
|
||||
```bash terminal icon="terminal"
|
||||
bun build --compile ./index.ts ./public/**/*.png
|
||||
```
|
||||
|
||||
Then, you can reference the files in your code:
|
||||
|
||||
```ts
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
import icon from "./public/assets/icon.png" with { type: "file" };
|
||||
import { file } from "bun";
|
||||
|
||||
@@ -392,7 +433,7 @@ This is honestly a workaround, and we expect to improve this in the future with
|
||||
|
||||
To get a list of all embedded files, use `Bun.embeddedFiles`:
|
||||
|
||||
```js
|
||||
```ts index.ts icon="/icons/typescript.svg"
|
||||
import "./icon.png" with { type: "file" };
|
||||
import { embeddedFiles } from "bun";
|
||||
|
||||
@@ -413,141 +454,40 @@ By default, embedded files have a content hash appended to their name. This is u
|
||||
|
||||
To disable the content hash, pass `--asset-naming` to `bun build --compile` like this:
|
||||
|
||||
```sh
|
||||
$ bun build --compile --asset-naming="[name].[ext]" ./index.ts
|
||||
```bash terminal icon="terminal"
|
||||
bun build --compile --asset-naming="[name].[ext]" ./index.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Minification
|
||||
|
||||
To trim down the size of the executable a little, pass `--minify` to `bun build --compile`. This uses Bun's minifier to reduce the code size. Overall though, Bun's binary is still way too big and we need to make it smaller.
|
||||
|
||||
## Using Bun.build() API
|
||||
|
||||
You can also generate standalone executables using the `Bun.build()` JavaScript API. This is useful when you need programmatic control over the build process.
|
||||
|
||||
### Basic usage
|
||||
|
||||
```js
|
||||
await Bun.build({
|
||||
entrypoints: ["./app.ts"],
|
||||
outdir: "./dist",
|
||||
compile: {
|
||||
target: "bun-windows-x64",
|
||||
outfile: "myapp.exe",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Windows metadata with Bun.build()
|
||||
|
||||
When targeting Windows, you can specify metadata through the `windows` object:
|
||||
|
||||
```js
|
||||
await Bun.build({
|
||||
entrypoints: ["./app.ts"],
|
||||
outdir: "./dist",
|
||||
compile: {
|
||||
target: "bun-windows-x64",
|
||||
outfile: "myapp.exe",
|
||||
windows: {
|
||||
title: "My Application",
|
||||
publisher: "My Company Inc",
|
||||
version: "1.2.3.4",
|
||||
description: "A powerful application built with Bun",
|
||||
copyright: "© 2024 My Company Inc",
|
||||
hideConsole: false, // Set to true for GUI applications
|
||||
icon: "./icon.ico", // Path to icon file
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Cross-compilation with Bun.build()
|
||||
|
||||
You can cross-compile for different platforms:
|
||||
|
||||
```js
|
||||
// Build for multiple platforms
|
||||
const platforms = [
|
||||
{ target: "bun-windows-x64", outfile: "app-windows.exe" },
|
||||
{ target: "bun-linux-x64", outfile: "app-linux" },
|
||||
{ target: "bun-darwin-arm64", outfile: "app-macos" },
|
||||
];
|
||||
|
||||
for (const platform of platforms) {
|
||||
await Bun.build({
|
||||
entrypoints: ["./app.ts"],
|
||||
outdir: "./dist",
|
||||
compile: platform,
|
||||
});
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
## Windows-specific flags
|
||||
|
||||
When compiling a standalone executable for Windows, there are several platform-specific options that can be used to customize the generated `.exe` file:
|
||||
When compiling a standalone executable on Windows, there are two platform-specific options that can be used to customize metadata on the generated `.exe` file:
|
||||
|
||||
### Visual customization
|
||||
- `--windows-icon=path/to/icon.ico` to customize the executable file icon.
|
||||
- `--windows-hide-console` to disable the background terminal, which can be used for applications that do not need a TTY.
|
||||
|
||||
- `--windows-icon=path/to/icon.ico` - Set the executable file icon
|
||||
- `--windows-hide-console` - Disable the background terminal window (useful for GUI applications)
|
||||
<Warning>These flags currently cannot be used when cross-compiling because they depend on Windows APIs.</Warning>
|
||||
|
||||
### Metadata customization
|
||||
|
||||
You can embed version information and other metadata into your Windows executable:
|
||||
|
||||
- `--windows-title <STR>` - Set the product name (appears in file properties)
|
||||
- `--windows-publisher <STR>` - Set the company name
|
||||
- `--windows-version <STR>` - Set the version number (e.g. "1.2.3.4")
|
||||
- `--windows-description <STR>` - Set the file description
|
||||
- `--windows-copyright <STR>` - Set the copyright information
|
||||
|
||||
#### Example with all metadata flags:
|
||||
|
||||
```sh
|
||||
bun build --compile ./app.ts \
|
||||
--outfile myapp.exe \
|
||||
--windows-title "My Application" \
|
||||
--windows-publisher "My Company Inc" \
|
||||
--windows-version "1.2.3.4" \
|
||||
--windows-description "A powerful application built with Bun" \
|
||||
--windows-copyright "© 2024 My Company Inc"
|
||||
```
|
||||
|
||||
This metadata will be visible in Windows Explorer when viewing the file properties:
|
||||
|
||||
1. Right-click the executable in Windows Explorer
|
||||
2. Select "Properties"
|
||||
3. Go to the "Details" tab
|
||||
|
||||
#### Version string format
|
||||
|
||||
The `--windows-version` flag accepts version strings in the following formats:
|
||||
|
||||
- `"1"` - Will be normalized to "1.0.0.0"
|
||||
- `"1.2"` - Will be normalized to "1.2.0.0"
|
||||
- `"1.2.3"` - Will be normalized to "1.2.3.0"
|
||||
- `"1.2.3.4"` - Full version format
|
||||
|
||||
Each version component must be a number between 0 and 65535.
|
||||
|
||||
{% callout %}
|
||||
|
||||
These flags currently cannot be used when cross-compiling because they depend on Windows APIs. They are only available when building on Windows itself.
|
||||
|
||||
{% /callout %}
|
||||
---
|
||||
|
||||
## Code signing on macOS
|
||||
|
||||
To codesign a standalone executable on macOS (which fixes Gatekeeper warnings), use the `codesign` command.
|
||||
|
||||
```sh
|
||||
$ codesign --deep --force -vvvv --sign "XXXXXXXXXX" ./myapp
|
||||
```bash terminal icon="terminal"
|
||||
codesign --deep --force -vvvv --sign "XXXXXXXXXX" ./myapp
|
||||
```
|
||||
|
||||
We recommend including an `entitlements.plist` file with JIT permissions.
|
||||
|
||||
```xml#entitlements.plist
|
||||
```xml icon="xml" title="info.plist"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
@@ -568,59 +508,28 @@ We recommend including an `entitlements.plist` file with JIT permissions.
|
||||
|
||||
To codesign with JIT support, pass the `--entitlements` flag to `codesign`.
|
||||
|
||||
```sh
|
||||
$ codesign --deep --force -vvvv --sign "XXXXXXXXXX" --entitlements entitlements.plist ./myapp
|
||||
```bash terminal icon="terminal"
|
||||
codesign --deep --force -vvvv --sign "XXXXXXXXXX" --entitlements entitlements.plist ./myapp
|
||||
```
|
||||
|
||||
After codesigning, verify the executable:
|
||||
|
||||
```sh
|
||||
$ codesign -vvv --verify ./myapp
|
||||
```bash terminal icon="terminal"
|
||||
codesign -vvv --verify ./myapp
|
||||
./myapp: valid on disk
|
||||
./myapp: satisfies its Designated Requirement
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
<Warning>Codesign support requires Bun v1.2.4 or newer.</Warning>
|
||||
|
||||
Codesign support requires Bun v1.2.4 or newer.
|
||||
|
||||
{% /callout %}
|
||||
|
||||
## Code splitting
|
||||
|
||||
Standalone executables support code splitting. Use `--compile` with `--splitting` to create an executable that loads code-split chunks at runtime.
|
||||
|
||||
```bash
|
||||
$ bun build --compile --splitting ./src/entry.ts --outdir ./build
|
||||
```
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```ts#src/entry.ts
|
||||
console.log("Entrypoint loaded");
|
||||
const lazy = await import("./lazy.ts");
|
||||
lazy.hello();
|
||||
```
|
||||
|
||||
```ts#src/lazy.ts
|
||||
export function hello() {
|
||||
console.log("Lazy module loaded");
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
```bash
|
||||
$ ./build/entry
|
||||
Entrypoint loaded
|
||||
Lazy module loaded
|
||||
```
|
||||
---
|
||||
|
||||
## Unsupported CLI arguments
|
||||
|
||||
Currently, 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`).
|
||||
- `--outdir` — use `outfile` instead.
|
||||
- `--splitting`
|
||||
- `--public-path`
|
||||
- `--target=node` or `--target=browser`
|
||||
- `--no-bundle` - we always bundle everything into the executable.
|
||||
@@ -1,418 +0,0 @@
|
||||
To get started, import HTML files and pass them to the `routes` option in `Bun.serve()`.
|
||||
|
||||
```ts
|
||||
import { sql, serve } from "bun";
|
||||
import dashboard from "./dashboard.html";
|
||||
import homepage from "./index.html";
|
||||
|
||||
const server = serve({
|
||||
routes: {
|
||||
// ** HTML imports **
|
||||
// Bundle & route index.html to "/". This uses HTMLRewriter to scan the HTML for `<script>` and `<link>` tags, run's Bun's JavaScript & CSS bundler on them, transpiles any TypeScript, JSX, and TSX, downlevels CSS with Bun's CSS parser and serves the result.
|
||||
"/": homepage,
|
||||
// Bundle & route dashboard.html to "/dashboard"
|
||||
"/dashboard": dashboard,
|
||||
|
||||
// ** API endpoints ** (Bun v1.2.3+ required)
|
||||
"/api/users": {
|
||||
async GET(req) {
|
||||
const users = await sql`SELECT * FROM users`;
|
||||
return Response.json(users);
|
||||
},
|
||||
async POST(req) {
|
||||
const { name, email } = await req.json();
|
||||
const [user] =
|
||||
await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`;
|
||||
return Response.json(user);
|
||||
},
|
||||
},
|
||||
"/api/users/:id": async req => {
|
||||
const { id } = req.params;
|
||||
const [user] = await sql`SELECT * FROM users WHERE id = ${id}`;
|
||||
return Response.json(user);
|
||||
},
|
||||
},
|
||||
|
||||
// Enable development mode for:
|
||||
// - Detailed error messages
|
||||
// - Hot reloading (Bun v1.2.3+ required)
|
||||
development: true,
|
||||
|
||||
// Prior to v1.2.3, the `fetch` option was used to handle all API requests. It is now optional.
|
||||
// async fetch(req) {
|
||||
// // Return 404 for unmatched routes
|
||||
// return new Response("Not Found", { status: 404 });
|
||||
// },
|
||||
});
|
||||
|
||||
console.log(`Listening on ${server.url}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ bun run app.ts
|
||||
```
|
||||
|
||||
## HTML imports are 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
|
||||
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()`.
|
||||
|
||||
```ts
|
||||
Bun.serve({
|
||||
routes: {
|
||||
"/": homepage,
|
||||
"/dashboard": dashboard,
|
||||
}
|
||||
|
||||
fetch(req) {
|
||||
// ... api requests
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When you make a request to `/dashboard` or `/`, Bun automatically bundles the `<script>` and `<link>` tags in the HTML files, exposes them as static routes, and serves the result.
|
||||
|
||||
An index.html file like this:
|
||||
|
||||
```html#index.html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
<link rel="stylesheet" href="./reset.css" />
|
||||
<link rel="stylesheet" href="./styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./sentry-and-preloads.ts"></script>
|
||||
<script type="module" src="./my-app.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Becomes something like this:
|
||||
|
||||
```html#index.html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
<link rel="stylesheet" href="/index-[hash].css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/index-[hash].js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### How to use with React
|
||||
|
||||
To use React in your client-side code, import `react-dom/client` and render your app.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```ts#src/backend.ts
|
||||
import dashboard from "../public/dashboard.html";
|
||||
import { serve } from "bun";
|
||||
|
||||
serve({
|
||||
routes: {
|
||||
"/": dashboard,
|
||||
},
|
||||
|
||||
async fetch(req) {
|
||||
// ...api requests
|
||||
return new Response("hello world");
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts#src/frontend.tsx
|
||||
import "./styles.css";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./app.tsx";
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const root = createRoot(document.getElementById("root"));
|
||||
root.render(<App />);
|
||||
});
|
||||
```
|
||||
|
||||
```html#public/dashboard.html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="../src/frontend.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
```css#src/styles.css
|
||||
body {
|
||||
background-color: red;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx#src/app.tsx
|
||||
export function App() {
|
||||
return <div>Hello World</div>;
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
### Development mode
|
||||
|
||||
When building locally, enable development mode by setting `development: true` in `Bun.serve()`.
|
||||
|
||||
```js-diff
|
||||
import homepage from "./index.html";
|
||||
import dashboard from "./dashboard.html";
|
||||
|
||||
Bun.serve({
|
||||
routes: {
|
||||
"/": homepage,
|
||||
"/dashboard": dashboard,
|
||||
}
|
||||
|
||||
+ development: true,
|
||||
|
||||
fetch(req) {
|
||||
// ... api requests
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When `development` is `true`, Bun will:
|
||||
|
||||
- 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
|
||||
|
||||
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()`.
|
||||
|
||||
```ts
|
||||
import homepage from "./index.html";
|
||||
|
||||
Bun.serve({
|
||||
// development can also be an object.
|
||||
development: {
|
||||
// Enable Hot Module Reloading
|
||||
hmr: true,
|
||||
|
||||
// Echo console logs from the browser to the terminal
|
||||
console: true,
|
||||
},
|
||||
|
||||
routes: {
|
||||
"/": homepage,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### 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.
|
||||
|
||||
##### 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.
|
||||
|
||||
```sh
|
||||
$ 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.
|
||||
|
||||
```ts
|
||||
import { serve } from "bun";
|
||||
import index from "./index.html";
|
||||
|
||||
serve({
|
||||
routes: { "/": index },
|
||||
});
|
||||
```
|
||||
|
||||
{% details summary="Internally, the `index` variable is a manifest object that looks something like this" %}
|
||||
|
||||
```json
|
||||
{
|
||||
"index": "./index.html",
|
||||
"files": [
|
||||
{
|
||||
"input": "index.html",
|
||||
"path": "./index-f2me3qnf.js",
|
||||
"loader": "js",
|
||||
"isEntry": true,
|
||||
"headers": {
|
||||
"etag": "eet6gn75",
|
||||
"content-type": "text/javascript;charset=utf-8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"input": "index.html",
|
||||
"path": "./index.html",
|
||||
"loader": "html",
|
||||
"isEntry": true,
|
||||
"headers": {
|
||||
"etag": "r9njjakd",
|
||||
"content-type": "text/html;charset=utf-8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"input": "index.html",
|
||||
"path": "./index-gysa5fmk.css",
|
||||
"loader": "css",
|
||||
"isEntry": true,
|
||||
"headers": {
|
||||
"etag": "50zb7x61",
|
||||
"content-type": "text/css;charset=utf-8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"input": "logo.svg",
|
||||
"path": "./logo-kygw735p.svg",
|
||||
"loader": "file",
|
||||
"isEntry": false,
|
||||
"headers": {
|
||||
"etag": "kygw735p",
|
||||
"content-type": "application/octet-stream"
|
||||
}
|
||||
},
|
||||
{
|
||||
"input": "react.svg",
|
||||
"path": "./react-ck11dneg.svg",
|
||||
"loader": "file",
|
||||
"isEntry": false,
|
||||
"headers": {
|
||||
"etag": "ck11dneg",
|
||||
"content-type": "application/octet-stream"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
{% /details %}
|
||||
|
||||
##### Runtime bundling
|
||||
|
||||
When adding a build step is too complicated, you can set `development: false` in `Bun.serve()`.
|
||||
|
||||
- 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.
|
||||
- Enables `Cache-Control` headers and `ETag` headers
|
||||
- Minifies JavaScript/TypeScript/TSX/JSX files
|
||||
|
||||
## Plugins
|
||||
|
||||
Bun's [bundler plugins](https://bun.com/docs/bundler/plugins) are also supported when bundling static routes.
|
||||
|
||||
To configure plugins for `Bun.serve`, add a `plugins` array in the `[serve.static]` section of your `bunfig.toml`.
|
||||
|
||||
### Using TailwindCSS in HTML routes
|
||||
|
||||
For example, enable TailwindCSS on your routes by installing and adding the `bun-plugin-tailwind` plugin:
|
||||
|
||||
```sh
|
||||
$ bun add bun-plugin-tailwind
|
||||
```
|
||||
|
||||
```toml#bunfig.toml
|
||||
[serve.static]
|
||||
plugins = ["bun-plugin-tailwind"]
|
||||
```
|
||||
|
||||
This will allow you to use TailwindCSS utility classes in your HTML and CSS files. All you need to do is import `tailwindcss` somewhere:
|
||||
|
||||
```html#index.html
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
<link rel="stylesheet" href="tailwindcss" />
|
||||
</head>
|
||||
<body>
|
||||
<!-- the rest of your HTML... -->
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Or in your CSS:
|
||||
|
||||
```css#style.css
|
||||
@import "tailwindcss";
|
||||
```
|
||||
|
||||
### Custom plugins
|
||||
|
||||
Any JS file or module which exports a [valid bundler plugin object](https://bun.com/docs/bundler/plugins#usage) (essentially an object with a `name` and `setup` field) can be placed inside the `plugins` array:
|
||||
|
||||
```toml#bunfig.toml
|
||||
[serve.static]
|
||||
plugins = ["./my-plugin-implementation.ts"]
|
||||
```
|
||||
|
||||
Bun will lazily resolve and load each plugin and use them to bundle your routes.
|
||||
|
||||
Note: 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.
|
||||
|
||||
## How this works
|
||||
|
||||
Bun uses [`HTMLRewriter`](/docs/api/html-rewriter) to scan for `<script>` and `<link>` tags in HTML files, uses them as entrypoints for [Bun's bundler](/docs/bundler), generates an optimized bundle for the JavaScript/TypeScript/TSX/JSX and CSS files, and serves the result.
|
||||
|
||||
1. **`<script>` processing**
|
||||
- Transpiles TypeScript, JSX, and TSX in `<script>` tags
|
||||
- Bundles imported dependencies
|
||||
- Generates sourcemaps for debugging
|
||||
- Minifies when `development` is not `true` in `Bun.serve()`
|
||||
|
||||
```html
|
||||
<script type="module" src="./counter.tsx"></script>
|
||||
```
|
||||
|
||||
2. **`<link>` processing**
|
||||
- Processes CSS imports and `<link>` tags
|
||||
- Concatenates CSS files
|
||||
- Rewrites `url` and asset paths to include content-addressable hashes in URLs
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="./styles.css" />
|
||||
```
|
||||
|
||||
3. **`<img>` & asset processing**
|
||||
- Links to assets are rewritten to include content-addressable hashes in URLs
|
||||
- Small assets in CSS files are inlined into `data:` URLs, reducing the total number of HTTP requests sent over the wire
|
||||
|
||||
4. **Rewrite HTML**
|
||||
- Combines all `<script>` tags into a single `<script>` tag with a content-addressable hash in the URL
|
||||
- Combines all `<link>` tags into a single `<link>` tag with a content-addressable hash in the URL
|
||||
- Outputs a new HTML file
|
||||
|
||||
5. **Serve**
|
||||
- All the output files from the bundler are exposed as static routes, using the same mechanism internally as when you pass a `Response` object to [`static` in `Bun.serve()`](/docs/api/http#static-routes).
|
||||
|
||||
This works similarly to how [`Bun.build` processes HTML files](/docs/bundler/html).
|
||||
|
||||
## This is a work in progress
|
||||
|
||||
- This doesn't support `bun build` yet. It also will in the future.
|
||||
1064
docs/bundler/fullstack.mdx
Normal file
1064
docs/bundler/fullstack.mdx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,32 +1,35 @@
|
||||
Hot Module Replacement (HMR) allows you to update modules in a running
|
||||
application without needing a full page reload. This preserves the application
|
||||
state and improves the development experience.
|
||||
---
|
||||
title: Hot reloading
|
||||
description: Hot Module Replacement (HMR) for Bun's development server
|
||||
---
|
||||
|
||||
HMR is enabled by default when using Bun's full-stack development server.
|
||||
Hot Module Replacement (HMR) allows you to update modules in a running application without needing a full page reload. This preserves the application state and improves the development experience.
|
||||
|
||||
<Note>HMR is enabled by default when using Bun's full-stack development server.</Note>
|
||||
|
||||
## `import.meta.hot` API Reference
|
||||
|
||||
Bun implements a client-side HMR API modeled after [Vite's `import.meta.hot` API](https://vitejs.dev/guide/api-hmr.html). It can be checked for with `if (import.meta.hot)`, tree-shaking it in production
|
||||
Bun implements a client-side HMR API modeled after [Vite's `import.meta.hot` API](https://vitejs.dev/guide/api-hmr.html). It can be checked for with `if (import.meta.hot)`, tree-shaking it in production.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
if (import.meta.hot) {
|
||||
// HMR APIs are available.
|
||||
}
|
||||
```
|
||||
|
||||
However, **this check is often not needed** as Bun will dead-code-eliminate
|
||||
calls to all of the HMR APIs in production builds.
|
||||
However, this check is often not needed as Bun will dead-code-eliminate calls to all of the HMR APIs in production builds.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
// This entire function call will be removed in production!
|
||||
import.meta.hot.dispose(() => {
|
||||
console.log("dispose");
|
||||
});
|
||||
```
|
||||
|
||||
<Warning>
|
||||
For this to work, Bun forces these APIs to be called without indirection. That means the following do not work:
|
||||
|
||||
```ts#invalid-hmr-usage.ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
// INVALID: Assigning `hot` to a variable
|
||||
const hot = import.meta.hot;
|
||||
hot.accept();
|
||||
@@ -46,32 +49,32 @@ import.meta.hot.accept();
|
||||
doSomething(import.meta.hot.data);
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
</Warning>
|
||||
|
||||
**Note** — The HMR API is still a work in progress. Some features are missing. HMR can be disabled in `Bun.serve` by setting the `development` option to `{ hmr: false }`.
|
||||
<Note>
|
||||
The HMR API is still a work in progress. Some features are missing. HMR can be disabled in `Bun.serve` by setting the development option to `{ hmr: false }`.
|
||||
</Note>
|
||||
|
||||
{% endcallout %}
|
||||
## API Methods
|
||||
|
||||
| | Method | Notes |
|
||||
| --- | ------------------ | --------------------------------------------------------------------- |
|
||||
| ✅ | `hot.accept()` | Indicate that a hot update can be replaced gracefully. |
|
||||
| ✅ | `hot.data` | Persist data between module evaluations. |
|
||||
| ✅ | `hot.dispose()` | Add a callback function to run when a module is about to be replaced. |
|
||||
| ❌ | `hot.invalidate()` | |
|
||||
| ✅ | `hot.on()` | Attach an event listener |
|
||||
| ✅ | `hot.off()` | Remove an event listener from `on`. |
|
||||
| ❌ | `hot.send()` | |
|
||||
| 🚧 | `hot.prune()` | **NOTE**: Callback is currently never called. |
|
||||
| ✅ | `hot.decline()` | No-op to match Vite's `import.meta.hot` |
|
||||
| Method | Status | Notes |
|
||||
| ------------------ | ------ | --------------------------------------------------------------------- |
|
||||
| `hot.accept()` | ✅ | Indicate that a hot update can be replaced gracefully. |
|
||||
| `hot.data` | ✅ | Persist data between module evaluations. |
|
||||
| `hot.dispose()` | ✅ | Add a callback function to run when a module is about to be replaced. |
|
||||
| `hot.invalidate()` | ❌ | |
|
||||
| `hot.on()` | ✅ | Attach an event listener |
|
||||
| `hot.off()` | ✅ | Remove an event listener from `on`. |
|
||||
| `hot.send()` | ❌ | |
|
||||
| `hot.prune()` | 🚧 | NOTE: Callback is currently never called. |
|
||||
| `hot.decline()` | ✅ | No-op to match Vite's `import.meta.hot` |
|
||||
|
||||
### `import.meta.hot.accept()`
|
||||
## import.meta.hot.accept()
|
||||
|
||||
The `accept()` method indicates that a module can be hot-replaced. When called
|
||||
without arguments, it indicates that this module can be replaced simply by
|
||||
re-evaluating the file. After a hot update, importers of this module will be
|
||||
automatically patched.
|
||||
The `accept()` method indicates that a module can be hot-replaced. When called without arguments, it indicates that this module can be replaced simply by re-evaluating the file. After a hot update, importers of this module will be automatically patched.
|
||||
|
||||
```ts#index.ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
// index.ts
|
||||
import { getCount } from "./foo.ts";
|
||||
|
||||
console.log("count is ", getCount());
|
||||
@@ -83,28 +86,21 @@ export function getNegativeCount() {
|
||||
}
|
||||
```
|
||||
|
||||
This creates a hot-reloading boundary for all of the files that `index.ts`
|
||||
imports. That means whenever `foo.ts` or any of its dependencies are saved, the
|
||||
update will bubble up to `index.ts` will re-evaluate. Files that import
|
||||
`index.ts` will then be patched to import the new version of
|
||||
`getNegativeCount()`. If only `index.ts` is updated, only the one file will be
|
||||
re-evaluated, and the counter in `foo.ts` is reused.
|
||||
This creates a hot-reloading boundary for all of the files that `index.ts` imports. That means whenever `foo.ts` or any of its dependencies are saved, the update will bubble up to `index.ts` will re-evaluate. Files that import `index.ts` will then be patched to import the new version of `getNegativeCount()`. If only `index.ts` is updated, only the one file will be re-evaluated, and the counter in `foo.ts` is reused.
|
||||
|
||||
This may be used in combination with `import.meta.hot.data` to transfer state
|
||||
from the previous module to the new one.
|
||||
This may be used in combination with `import.meta.hot.data` to transfer state from the previous module to the new one.
|
||||
|
||||
When no modules call `import.meta.hot.accept()` (and there isn't React Fast
|
||||
Refresh or a plugin calling it for you), the page will reload when the file
|
||||
updates, and a console warning shows which files were invalidated. This warning
|
||||
is safe to ignore if it makes more sense to rely on full page reloads.
|
||||
<Info>
|
||||
When no modules call `import.meta.hot.accept()` (and there isn't React Fast Refresh or a plugin calling it for you),
|
||||
the page will reload when the file updates, and a console warning shows which files were invalidated. This warning is
|
||||
safe to ignore if it makes more sense to rely on full page reloads.
|
||||
</Info>
|
||||
|
||||
#### With callback
|
||||
### With callback
|
||||
|
||||
When provided one callback, `import.meta.hot.accept` will function how it does
|
||||
in Vite. Instead of patching the importers of this module, it will call the
|
||||
callback with the new module.
|
||||
When provided one callback, `import.meta.hot.accept` will function how it does in Vite. Instead of patching the importers of this module, it will call the callback with the new module.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
export const count = 0;
|
||||
|
||||
import.meta.hot.accept(newModule => {
|
||||
@@ -115,11 +111,13 @@ import.meta.hot.accept(newModule => {
|
||||
});
|
||||
```
|
||||
|
||||
Prefer using `import.meta.hot.accept()` without an argument as it usually makes your code easier to understand.
|
||||
<Tip>
|
||||
Prefer using `import.meta.hot.accept()` without an argument as it usually makes your code easier to understand.
|
||||
</Tip>
|
||||
|
||||
#### Accepting other modules
|
||||
### Accepting other modules
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { count } from "./foo";
|
||||
|
||||
import.meta.hot.accept("./foo", () => {
|
||||
@@ -131,9 +129,9 @@ import.meta.hot.accept("./foo", () => {
|
||||
|
||||
Indicates that a dependency's module can be accepted. When the dependency is updated, the callback will be called with the new module.
|
||||
|
||||
#### With multiple dependencies
|
||||
### With multiple dependencies
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import.meta.hot.accept(["./foo", "./bar"], newModules => {
|
||||
// newModules is an array where each item corresponds to the updated module
|
||||
// or undefined if that module had a syntax error
|
||||
@@ -142,33 +140,33 @@ import.meta.hot.accept(["./foo", "./bar"], newModules => {
|
||||
|
||||
Indicates that multiple dependencies' modules can be accepted. This variant accepts an array of dependencies, where the callback will receive the updated modules, and `undefined` for any that had errors.
|
||||
|
||||
### `import.meta.hot.data`
|
||||
## import.meta.hot.data
|
||||
|
||||
`import.meta.hot.data` maintains state between module instances during hot
|
||||
replacement, enabling data transfer from previous to new versions. When
|
||||
`import.meta.hot.data` is written into, Bun will also mark this module as
|
||||
capable of self-accepting (equivalent of calling `import.meta.hot.accept()`).
|
||||
`import.meta.hot.data` maintains state between module instances during hot replacement, enabling data transfer from previous to new versions. When `import.meta.hot.data` is written into, Bun will also mark this module as capable of self-accepting (equivalent of calling `import.meta.hot.accept()`).
|
||||
|
||||
```ts
|
||||
```jsx title="index.ts" icon="/icons/typescript.svg"
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./app";
|
||||
|
||||
const root = import.meta.hot.data.root ??= createRoot(elem);
|
||||
const root = (import.meta.hot.data.root ??= createRoot(elem));
|
||||
root.render(<App />); // re-use an existing root
|
||||
```
|
||||
|
||||
In production, `data` is inlined to be `{}`, meaning it cannot be used as a state holder.
|
||||
|
||||
The above pattern is recommended for stateful modules because Bun knows it can minify `{}.prop ??= value` into `value` in production.
|
||||
<Tip>
|
||||
The above pattern is recommended for stateful modules because Bun knows it can minify `{}.prop ??= value` into `value`
|
||||
in production.
|
||||
</Tip>
|
||||
|
||||
### `import.meta.hot.dispose()`
|
||||
## import.meta.hot.dispose()
|
||||
|
||||
Attaches an on-dispose callback. This is called:
|
||||
|
||||
- Just before the module is replaced with another copy (before the next is loaded)
|
||||
- After the module is detached (removing all imports to this module, see `import.meta.hot.prune()`)
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
const sideEffect = setupSideEffect();
|
||||
|
||||
import.meta.hot.dispose(() => {
|
||||
@@ -176,21 +174,17 @@ import.meta.hot.dispose(() => {
|
||||
});
|
||||
```
|
||||
|
||||
This callback is not called on route navigation or when the browser tab closes.
|
||||
<Warning>This callback is not called on route navigation or when the browser tab closes.</Warning>
|
||||
|
||||
Returning a promise will delay module replacement until the module is disposed.
|
||||
All dispose callbacks are called in parallel.
|
||||
Returning a promise will delay module replacement until the module is disposed. All dispose callbacks are called in parallel.
|
||||
|
||||
### `import.meta.hot.prune()`
|
||||
## import.meta.hot.prune()
|
||||
|
||||
Attaches an on-prune callback. This is called when all imports to this module
|
||||
are removed, but the module was previously loaded.
|
||||
Attaches an on-prune callback. This is called when all imports to this module are removed, but the module was previously loaded.
|
||||
|
||||
This can be used to clean up resources that were created when the module was
|
||||
loaded. Unlike `import.meta.hot.dispose()`, this pairs much better with `accept`
|
||||
and `data` to manage stateful resources. A full example managing a `WebSocket`:
|
||||
This can be used to clean up resources that were created when the module was loaded. Unlike `import.meta.hot.dispose()`, this pairs much better with `accept` and `data` to manage stateful resources. A full example managing a WebSocket:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { something } from "./something";
|
||||
|
||||
// Initialize or re-use a WebSocket connection
|
||||
@@ -202,15 +196,16 @@ import.meta.hot.prune(() => {
|
||||
});
|
||||
```
|
||||
|
||||
If `dispose` was used instead, the WebSocket would close and re-open on every
|
||||
hot update. Both versions of the code will prevent page reloads when imported
|
||||
files are updated.
|
||||
<Info>
|
||||
If `dispose` was used instead, the WebSocket would close and re-open on every hot update. Both versions of the code
|
||||
will prevent page reloads when imported files are updated.
|
||||
</Info>
|
||||
|
||||
### `import.meta.hot.on()` and `off()`
|
||||
## import.meta.hot.on() and off()
|
||||
|
||||
`on()` and `off()` are used to listen for events from the HMR runtime. Event names are prefixed with a prefix so that plugins do not conflict with each other.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import.meta.hot.on("bun:beforeUpdate", () => {
|
||||
console.log("before a hot update");
|
||||
});
|
||||
@@ -218,7 +213,7 @@ import.meta.hot.on("bun:beforeUpdate", () => {
|
||||
|
||||
When a file is replaced, all of its event listeners are automatically removed.
|
||||
|
||||
A list of all built-in events:
|
||||
### Built-in events
|
||||
|
||||
| Event | Emitted when |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------------- |
|
||||
@@ -231,4 +226,4 @@ A list of all built-in events:
|
||||
| `bun:ws:disconnect` | when the HMR WebSocket connection is lost. This can indicate the development server is offline. |
|
||||
| `bun:ws:connect` | when the HMR WebSocket connects or re-connects. |
|
||||
|
||||
For compatibility with Vite, the above events are also available via `vite:*` prefix instead of `bun:*`.
|
||||
<Note>For compatibility with Vite, the above events are also available via `vite:*` prefix instead of `bun:*`.</Note>
|
||||
@@ -1,6 +1,11 @@
|
||||
---
|
||||
title: HTML & static sites
|
||||
description: Build static sites, landing pages, and web applications with Bun's bundler
|
||||
---
|
||||
|
||||
Bun's bundler has first-class support for HTML. Build static sites, landing pages, and web applications with zero configuration. Just point Bun at your HTML file and it handles everything else.
|
||||
|
||||
```html#index.html
|
||||
```html title="index.html" icon="file-code"
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -15,7 +20,16 @@ Bun's bundler has first-class support for HTML. Build static sites, landing page
|
||||
|
||||
To get started, pass HTML files to `bun`.
|
||||
|
||||
{% bunDevServerTerminal alt="bun ./index.html" path="./index.html" routes="" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun ./index.html
|
||||
```
|
||||
|
||||
```
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
Bun's development server provides powerful features with zero configuration:
|
||||
|
||||
@@ -26,19 +40,26 @@ Bun's development server provides powerful features with zero configuration:
|
||||
- **Plugins** - Plugins for TailwindCSS and more
|
||||
- **ESM & CommonJS** - Use ESM and CommonJS in your JavaScript, TypeScript, and JSX files
|
||||
- **CSS Bundling & Minification** - Bundles CSS from `<link>` tags and `@import` statements
|
||||
- **Asset Management**
|
||||
- Automatic copying & hashing of images and assets
|
||||
- Rewrites asset paths in JavaScript, CSS, and HTML
|
||||
- **Asset Management** - Automatic copying & hashing of images and assets; Rewrites asset paths in JavaScript, CSS, and HTML
|
||||
|
||||
## Single Page Apps (SPA)
|
||||
|
||||
When you pass a single .html file to Bun, Bun will use it as a fallback route for all paths. This makes it perfect for single page apps that use client-side routing:
|
||||
When you pass a single `.html` file to Bun, Bun will use it as a fallback route for all paths. This makes it perfect for single page apps that use client-side routing:
|
||||
|
||||
{% bunDevServerTerminal alt="bun index.html" path="index.html" routes="" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun index.html
|
||||
```
|
||||
|
||||
```
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
Your React or other SPA will work out of the box — no configuration needed. All routes like `/about`, `/users/123`, etc. will serve the same HTML file, letting your client-side router handle the navigation.
|
||||
|
||||
```html#index.html
|
||||
```html title="index.html" icon="file-code"
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -53,9 +74,21 @@ Your React or other SPA will work out of the box — no configuration needed. Al
|
||||
|
||||
## Multi-page apps (MPA)
|
||||
|
||||
Some projects have several separate routes or HTML files as entry points. To support multiple entry points, pass them all to `bun`
|
||||
Some projects have several separate routes or HTML files as entry points. To support multiple entry points, pass them all to `bun`:
|
||||
|
||||
{% bunDevServerTerminal alt="bun ./index.html ./about.html" path="./index.html ./about.html" routes="[{\"path\": \"/\", \"file\": \"./index.html\"}, {\"path\": \"/about\", \"file\": \"./about.html\"}]" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun ./index.html ./about.html
|
||||
```
|
||||
|
||||
```txt
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Routes:
|
||||
/ ./index.html
|
||||
/about ./about.html
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
This will serve:
|
||||
|
||||
@@ -66,19 +99,44 @@ This will serve:
|
||||
|
||||
To specify multiple files, you can use glob patterns that end in `.html`:
|
||||
|
||||
{% bunDevServerTerminal alt="bun ./**/*.html" path="./**/*.html" routes="[{\"path\": \"/\", \"file\": \"./index.html\"}, {\"path\": \"/about\", \"file\": \"./about.html\"}]" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun ./**/*.html
|
||||
```
|
||||
|
||||
```
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Routes:
|
||||
/ ./index.html
|
||||
/about ./about.html
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
### Path normalization
|
||||
|
||||
The base path is chosen from the longest common prefix among all the files.
|
||||
|
||||
{% bunDevServerTerminal alt="bun ./index.html ./about/index.html ./about/foo/index.html" path="./index.html ./about/index.html ./about/foo/index.html" routes="[{\"path\": \"/\", \"file\": \"./index.html\"}, {\"path\": \"/about\", \"file\": \"./about/index.html\"}, {\"path\": \"/about/foo\", \"file\": \"./about/foo/index.html\"}]" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun ./index.html ./about/index.html ./about/foo/index.html
|
||||
```
|
||||
|
||||
```
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Routes:
|
||||
/ ./index.html
|
||||
/about ./about/index.html
|
||||
/about/foo ./about/foo/index.html
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
## JavaScript, TypeScript, and JSX
|
||||
|
||||
Bun's transpiler natively implements JavaScript, TypeScript, and JSX support. [Learn more about loaders in Bun](/docs/bundler/loaders).
|
||||
Bun's transpiler natively implements JavaScript, TypeScript, and JSX support. Learn more about loaders in Bun.
|
||||
|
||||
Bun's transpiler is also used at runtime.
|
||||
<Note>Bun's transpiler is also used at runtime.</Note>
|
||||
|
||||
### ES Modules & CommonJS
|
||||
|
||||
@@ -86,7 +144,7 @@ You can use ESM and CJS in your JavaScript, TypeScript, and JSX files. Bun will
|
||||
|
||||
There is no pre-build or separate optimization step. It's all done at the same time.
|
||||
|
||||
Learn more about [module resolution in Bun](/docs/runtime/modules).
|
||||
Learn more about module resolution in Bun.
|
||||
|
||||
## CSS
|
||||
|
||||
@@ -96,7 +154,9 @@ It's also a CSS bundler. You can use `@import` in your CSS files to import other
|
||||
|
||||
For example:
|
||||
|
||||
```css#styles.css
|
||||
<CodeGroup>
|
||||
|
||||
```css styles.css icon="file-code"
|
||||
@import "./abc.css";
|
||||
|
||||
.container {
|
||||
@@ -104,15 +164,17 @@ For example:
|
||||
}
|
||||
```
|
||||
|
||||
```css#abc.css
|
||||
```css abc.css
|
||||
body {
|
||||
background-color: red;
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
This outputs:
|
||||
|
||||
```css#styles.css
|
||||
```css
|
||||
body {
|
||||
background-color: red;
|
||||
}
|
||||
@@ -126,7 +188,7 @@ body {
|
||||
|
||||
You can reference local assets in your CSS files.
|
||||
|
||||
```css#styles.css
|
||||
```css styles.css icon="file-code"
|
||||
body {
|
||||
background-image: url("./logo.png");
|
||||
}
|
||||
@@ -134,7 +196,7 @@ body {
|
||||
|
||||
This will copy `./logo.png` to the output directory and rewrite the path in the CSS file to include a content hash.
|
||||
|
||||
```css#styles.css
|
||||
```css styles.css icon="file-code"
|
||||
body {
|
||||
background-image: url("./logo-[ABC123].png");
|
||||
}
|
||||
@@ -144,7 +206,7 @@ body {
|
||||
|
||||
To associate a CSS file with a JavaScript file, you can import it in your JavaScript file.
|
||||
|
||||
```ts#app.ts
|
||||
```ts app.ts icon="/icons/typescript.svg"
|
||||
import "./styles.css";
|
||||
import "./more-styles.css";
|
||||
```
|
||||
@@ -159,84 +221,57 @@ The dev server supports plugins.
|
||||
|
||||
To use TailwindCSS, install the `bun-plugin-tailwind` plugin:
|
||||
|
||||
```bash
|
||||
```bash terminal icon="terminal"
|
||||
# Or any npm client
|
||||
$ bun install --dev bun-plugin-tailwind
|
||||
bun install --dev bun-plugin-tailwind
|
||||
```
|
||||
|
||||
Then, add the plugin to your `bunfig.toml`:
|
||||
|
||||
```toml
|
||||
```toml title="bunfig.toml" icon="settings"
|
||||
[serve.static]
|
||||
plugins = ["bun-plugin-tailwind"]
|
||||
```
|
||||
|
||||
Then, reference TailwindCSS in your HTML via `<link>` tag, `@import` in CSS, or `import` in JavaScript.
|
||||
Then, reference TailwindCSS in your HTML via `<link>` tag, `@import` in CSS, or import in JavaScript.
|
||||
|
||||
{% codetabs %}
|
||||
<Tabs>
|
||||
<Tab title="index.html">
|
||||
```html title="index.html" icon="file-code"
|
||||
{/* Reference TailwindCSS in your HTML */}
|
||||
<link rel="stylesheet" href="tailwindcss" />
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="styles.css">```css title="styles.css" icon="file-code" @import "tailwindcss"; ```</Tab>
|
||||
<Tab title="app.ts">```ts title="app.ts" icon="/icons/typescript.svg" import "tailwindcss"; ```</Tab>
|
||||
</Tabs>
|
||||
|
||||
```html#index.html
|
||||
<!-- Reference TailwindCSS in your HTML -->
|
||||
<link rel="stylesheet" href="tailwindcss" />
|
||||
```
|
||||
<Info>Only one of those are necessary, not all three.</Info>
|
||||
|
||||
```css#styles.css
|
||||
/* Import TailwindCSS in your CSS */
|
||||
@import "tailwindcss";
|
||||
```
|
||||
|
||||
```ts#app.ts
|
||||
/* Import TailwindCSS in your JavaScript */
|
||||
import "tailwindcss";
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
Only one of those are necessary, not all three.
|
||||
|
||||
### Echo console logs from browser to terminal
|
||||
## Echo console logs from browser to terminal
|
||||
|
||||
Bun's dev server supports streaming console logs from the browser to the terminal.
|
||||
|
||||
To enable, pass the `--console` CLI flag.
|
||||
|
||||
{% bunDevServerTerminal alt="bun ./index.html --console" path="./index.html --console" routes="" /%}
|
||||
```bash terminal icon="terminal"
|
||||
bun ./index.html --console
|
||||
```
|
||||
|
||||
```
|
||||
Bun v1.2.20
|
||||
ready in 6.62ms
|
||||
→ http://localhost:3000/
|
||||
Press h + Enter to show shortcuts
|
||||
```
|
||||
|
||||
Each call to `console.log` or `console.error` will be broadcast to the terminal that started the server. This is useful to see errors from the browser in the same place you run your server. This is also useful for AI agents that watch terminal output.
|
||||
|
||||
Internally, this reuses the existing WebSocket connection from hot module reloading to send the logs.
|
||||
|
||||
### Edit files in the browser
|
||||
## Edit files in the browser
|
||||
|
||||
Bun's frontend dev server has support for [Automatic Workspace Folders](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md) in Chrome DevTools, which lets you save edits to files in the browser.
|
||||
|
||||
{% image src="/images/bun-chromedevtools.gif" alt="Bun's frontend dev server has support for Automatic Workspace Folders in Chrome DevTools, which lets you save edits to files in the browser." /%}
|
||||
|
||||
{% details summary="How it works" %}
|
||||
|
||||
Bun's dev server automatically adds a `/.well-known/appspecific/com.chrome.devtools.json` route to the server.
|
||||
|
||||
This route returns a JSON object with the following shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"workspace": {
|
||||
"root": "/path/to/your/project",
|
||||
"uuid": "a-unique-identifier-for-this-workspace"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For security reasons, this is only enabled when:
|
||||
|
||||
1. The request is coming from localhost, 127.0.0.1, or ::1.
|
||||
2. Hot Module Reloading is enabled.
|
||||
3. The `chromeDevToolsAutomaticWorkspaceFolders` flag is set to `true` or `undefined`.
|
||||
4. There are no other routes that match the request.
|
||||
|
||||
You can disable this by passing `development: { chromeDevToolsAutomaticWorkspaceFolders: false }` in `Bun.serve`'s options.
|
||||
|
||||
{% /details %}
|
||||
Bun's frontend dev server has support for Automatic Workspace Folders in Chrome DevTools, which lets you save edits to files in the browser.
|
||||
|
||||
## Keyboard Shortcuts
|
||||
|
||||
@@ -244,45 +279,45 @@ While the server is running:
|
||||
|
||||
- `o + Enter` - Open in browser
|
||||
- `c + Enter` - Clear console
|
||||
- `q + Enter` (or Ctrl+C) - Quit server
|
||||
- `q + Enter` (or `Ctrl+C`) - Quit server
|
||||
|
||||
## Build for Production
|
||||
|
||||
When you're ready to deploy, use `bun build` to create optimized production bundles:
|
||||
|
||||
{% codetabs %}
|
||||
<Tabs>
|
||||
<Tab title="CLI">
|
||||
```bash terminal icon="terminal"
|
||||
bun build ./index.html --minify --outdir=dist
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="API">
|
||||
```ts title="build.ts" icon="/icons/typescript.svg"
|
||||
await Bun.build({
|
||||
entrypoints: ["./index.html"],
|
||||
outdir: "./dist",
|
||||
minify: true,
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
```bash#CLI
|
||||
$ bun build ./index.html --minify --outdir=dist
|
||||
```
|
||||
|
||||
```ts#API
|
||||
Bun.build({
|
||||
entrypoints: ["./index.html"],
|
||||
outdir: "./dist",
|
||||
minify: {
|
||||
whitespace: true,
|
||||
identifiers: true,
|
||||
syntax: true,
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
Currently, plugins are only supported through `Bun.build`'s API or through `bunfig.toml` with the frontend dev server - not yet supported in `bun build`'s CLI.
|
||||
<Warning>
|
||||
Currently, plugins are only supported through `Bun.build`'s API or through `bunfig.toml` with the frontend dev server
|
||||
- not yet supported in `bun build`'s CLI.
|
||||
</Warning>
|
||||
|
||||
### Watch Mode
|
||||
|
||||
You can run `bun build --watch` to watch for changes and rebuild automatically. This works nicely for library development.
|
||||
|
||||
You've never seen a watch mode this fast.
|
||||
<Info>You've never seen a watch mode this fast.</Info>
|
||||
|
||||
### Plugin API
|
||||
## Plugin API
|
||||
|
||||
Need more control? Configure the bundler through the JavaScript API and use Bun's builtin `HTMLRewriter` to preprocess HTML.
|
||||
|
||||
```ts
|
||||
```ts title="build.ts" icon="/icons/typescript.svg"
|
||||
await Bun.build({
|
||||
entrypoints: ["./index.html"],
|
||||
outdir: "./dist",
|
||||
@@ -322,28 +357,30 @@ await Bun.build({
|
||||
|
||||
Bun automatically handles all common web assets:
|
||||
|
||||
- Scripts (`<script src>`) are run through Bun's JavaScript/TypeScript/JSX bundler
|
||||
- Stylesheets (`<link rel="stylesheet">`) are run through Bun's CSS parser & bundler
|
||||
- Images (`<img>`, `<picture>`) are copied and hashed
|
||||
- Media (`<video>`, `<audio>`, `<source>`) are copied and hashed
|
||||
- **Scripts** (`<script src>`) are run through Bun's JavaScript/TypeScript/JSX bundler
|
||||
- **Stylesheets** (`<link rel="stylesheet">`) are run through Bun's CSS parser & bundler
|
||||
- **Images** (`<img>`, `<picture>`) are copied and hashed
|
||||
- **Media** (`<video>`, `<audio>`, `<source>`) are copied and hashed
|
||||
- Any `<link>` tag with an `href` attribute pointing to a local file is rewritten to the new path, and hashed
|
||||
|
||||
All paths are resolved relative to your HTML file, making it easy to organize your project however you want.
|
||||
|
||||
## This is a work in progress
|
||||
|
||||
<Warning>
|
||||
**This is a work in progress**
|
||||
- Need more plugins
|
||||
- Need more configuration options for things like asset handling
|
||||
- Need a way to configure CORS, headers, etc.
|
||||
|
||||
If you want to submit a PR, most of the [code is here](https://github.com/oven-sh/bun/blob/main/src/js/internal/html.ts). You could even copy paste that file into your project and use it as a starting point.
|
||||
If you want to submit a PR, most of the code is [here](https://github.com/oven-sh/bun/blob/main/src/bun.js/api/bun/html-rewriter.ts). You could even copy paste that file into your project and use it as a starting point.
|
||||
|
||||
</Warning>
|
||||
|
||||
## How this works
|
||||
|
||||
This is a small wrapper around Bun's support for HTML imports in JavaScript.
|
||||
|
||||
### Adding a backend to your frontend
|
||||
## Adding a backend to your frontend
|
||||
|
||||
To add a backend to your frontend, you can use the `"routes"` option in `Bun.serve`.
|
||||
To add a backend to your frontend, you can use the "routes" option in `Bun.serve`.
|
||||
|
||||
Learn more in [the full-stack docs](/docs/bundler/fullstack).
|
||||
Learn more in the full-stack docs.
|
||||
File diff suppressed because it is too large
Load Diff
1499
docs/bundler/index.mdx
Normal file
1499
docs/bundler/index.mdx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,75 +0,0 @@
|
||||
<!-- This document is a work in progress. It's not currently included in the actual docs. -->
|
||||
|
||||
The goal of this document is to break down why bundling is necessary, how it works, and how the bundler became such a key part of modern JavaScript development. The content is not specific to Bun's bundler, but is rather aimed at anyone looking for a greater understanding of how bundlers work and, by extension, how most modern frameworks are implemented.
|
||||
|
||||
## What is bundling
|
||||
|
||||
With the adoption of ECMAScript modules (ESM), browsers can now resolve `import`/`export` statements in JavaScript files loaded via `<script>` tags.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```html#index.html
|
||||
<html>
|
||||
<head>
|
||||
<script type="module" src="/index.js" ></script>
|
||||
</head>
|
||||
</html>
|
||||
```
|
||||
|
||||
```js#index.js
|
||||
import {sayHello} from "./hello.js";
|
||||
|
||||
sayHello();
|
||||
```
|
||||
|
||||
```js#hello.js
|
||||
export function sayHello() {
|
||||
console.log("Hello, world!");
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
When a user visits this website, the files are loaded in the following order:
|
||||
|
||||
{% image src="/images/module_loading_unbundled.png" /%}
|
||||
|
||||
{% callout %}
|
||||
**Relative imports** — Relative imports are resolved relative to the URL of the importing file. Because we're importing `./hello.js` from `/index.js`, the browser resolves it to `/hello.js`. If instead we'd imported `./hello.js` from `/src/index.js`, the browser would have resolved it to `/src/hello.js`.
|
||||
{% /callout %}
|
||||
|
||||
This approach works, it requires three round-trip HTTP requests before the browser is ready to render the page. On slow internet connections, this may add up to a non-trivial delay.
|
||||
|
||||
This example is extremely simplistic. A modern app may be loading dozens of modules from `node_modules`, each consisting of hundred of files. Loading each of these files with a separate HTTP request becomes untenable very quickly. While most of these requests will be running in parallel, the number of round-trip requests can still be very high; plus, there are limits on how many simultaneous requests a browser can make.
|
||||
|
||||
{% callout %}
|
||||
Some recent advances like modulepreload and HTTP/3 are intended to solve some of these problems, but at the moment bundling is still the most performant approach.
|
||||
{% /callout %}
|
||||
|
||||
The answer: bundling.
|
||||
|
||||
## Entrypoints
|
||||
|
||||
A bundler accepts an "entrypoint" to your source code (in this case, `/index.js`) and outputs a single file containing all of the code needed to run your app. If does so by parsing your source code, reading the `import`/`export` statements, and building a "module graph" of your app's dependencies.
|
||||
|
||||
{% image src="/images/bundling.png" /%}
|
||||
|
||||
We can now load `/bundle.js` from our `index.html` file and eliminate a round trip request, decreasing load times for our app.
|
||||
|
||||
{% image src="/images/module_loading_bundled.png" /%}
|
||||
|
||||
## Loaders
|
||||
|
||||
Bundlers typically have some set of built-in "loaders".
|
||||
|
||||
## Transpilation
|
||||
|
||||
The JavaScript files above are just that: plain JavaScript. They can be directly executed by any modern browser.
|
||||
|
||||
But modern tooling goes far beyond HTML, JavaScript, and CSS. JSX, TypeScript, and PostCSS/CSS-in-JS are all popular technologies that involve non-standard syntax that must be converted into vanilla JavaScript and CSS before if can be consumed by a browser.
|
||||
|
||||
## Chunking
|
||||
|
||||
## Module resolution
|
||||
|
||||
## Plugins
|
||||
@@ -1,410 +0,0 @@
|
||||
The Bun bundler implements a set of default loaders out of the box. As a rule of thumb, the bundler and the runtime both support the same set of file types out of the box.
|
||||
|
||||
`.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` `.toml` `.json` `.yaml` `.yml` `.txt` `.wasm` `.node` `.html`
|
||||
|
||||
Bun uses the file extension to determine which built-in _loader_ should be used to parse the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building [plugins](https://bun.com/docs/bundler/plugins) that extend Bun with custom loaders.
|
||||
|
||||
You can explicitly specify which loader to use using the 'loader' import attribute.
|
||||
|
||||
```ts
|
||||
import my_toml from "./my_file" with { loader: "toml" };
|
||||
```
|
||||
|
||||
## Built-in loaders
|
||||
|
||||
### `js`
|
||||
|
||||
**JavaScript**. Default for `.cjs` and `.mjs`.
|
||||
|
||||
Parses the code and applies a set of default transforms like dead-code elimination and tree shaking. Note that Bun does not attempt to down-convert syntax at the moment.
|
||||
|
||||
### `jsx`
|
||||
|
||||
**JavaScript + JSX.**. Default for `.js` and `.jsx`.
|
||||
|
||||
Same as the `js` loader, but JSX syntax is supported. By default, JSX is down-converted to plain JavaScript; the details of how this is done depends on the `jsx*` compiler options in your `tsconfig.json`. Refer to the TypeScript documentation [on JSX](https://www.typescriptlang.org/docs/handbook/jsx.html) for more information.
|
||||
|
||||
### `ts`
|
||||
|
||||
**TypeScript loader**. Default for `.ts`, `.mts`, and `.cts`.
|
||||
|
||||
Strips out all TypeScript syntax, then behaves identically to the `js` loader. Bun does not perform typechecking.
|
||||
|
||||
### `tsx`
|
||||
|
||||
**TypeScript + JSX loader**. Default for `.tsx`. Transpiles both TypeScript and JSX to vanilla JavaScript.
|
||||
|
||||
### `json`
|
||||
|
||||
**JSON loader**. Default for `.json`.
|
||||
|
||||
JSON files can be directly imported.
|
||||
|
||||
```ts
|
||||
import pkg from "./package.json";
|
||||
pkg.name; // => "my-package"
|
||||
```
|
||||
|
||||
During bundling, the parsed JSON is inlined into the bundle as a JavaScript object.
|
||||
|
||||
```ts
|
||||
var pkg = {
|
||||
name: "my-package",
|
||||
// ... other fields
|
||||
};
|
||||
pkg.name;
|
||||
```
|
||||
|
||||
If a `.json` file is passed as an entrypoint to the bundler, it will be converted to a `.js` module that `export default`s the parsed object.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```json#Input
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 35,
|
||||
"email": "johndoe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
```js#Output
|
||||
export default {
|
||||
name: "John Doe",
|
||||
age: 35,
|
||||
email: "johndoe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
### `toml`
|
||||
|
||||
**TOML loader**. Default for `.toml`.
|
||||
|
||||
TOML files can be directly imported. Bun will parse them with its fast native TOML parser.
|
||||
|
||||
```ts
|
||||
import config from "./bunfig.toml";
|
||||
config.logLevel; // => "debug"
|
||||
|
||||
// via import attribute:
|
||||
// import myCustomTOML from './my.config' with {type: "toml"};
|
||||
```
|
||||
|
||||
During bundling, the parsed TOML is inlined into the bundle as a JavaScript object.
|
||||
|
||||
```ts
|
||||
var config = {
|
||||
logLevel: "debug",
|
||||
// ...other fields
|
||||
};
|
||||
config.logLevel;
|
||||
```
|
||||
|
||||
If a `.toml` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the parsed object.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```toml#Input
|
||||
name = "John Doe"
|
||||
age = 35
|
||||
email = "johndoe@example.com"
|
||||
```
|
||||
|
||||
```js#Output
|
||||
export default {
|
||||
name: "John Doe",
|
||||
age: 35,
|
||||
email: "johndoe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
### `yaml`
|
||||
|
||||
**YAML loader**. Default for `.yaml` and `.yml`.
|
||||
|
||||
YAML files can be directly imported. Bun will parse them with its fast native YAML parser.
|
||||
|
||||
```ts
|
||||
import config from "./config.yaml";
|
||||
config.database.host; // => "localhost"
|
||||
|
||||
// via import attribute:
|
||||
// import myCustomYAML from './my.config' with {type: "yaml"};
|
||||
```
|
||||
|
||||
During bundling, the parsed YAML is inlined into the bundle as a JavaScript object.
|
||||
|
||||
```ts
|
||||
var config = {
|
||||
database: {
|
||||
host: "localhost",
|
||||
port: 5432,
|
||||
},
|
||||
// ...other fields
|
||||
};
|
||||
config.database.host;
|
||||
```
|
||||
|
||||
If a `.yaml` or `.yml` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the parsed object.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```yaml#Input
|
||||
name: John Doe
|
||||
age: 35
|
||||
email: johndoe@example.com
|
||||
```
|
||||
|
||||
```js#Output
|
||||
export default {
|
||||
name: "John Doe",
|
||||
age: 35,
|
||||
email: "johndoe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
For more details on YAML support including the runtime API `Bun.YAML.parse()`, see the [YAML API documentation](/docs/api/yaml).
|
||||
|
||||
### `text`
|
||||
|
||||
**Text loader**. Default for `.txt`.
|
||||
|
||||
The contents of the text file are read and inlined into the bundle as a string.
|
||||
Text files can be directly imported. The file is read and returned as a string.
|
||||
|
||||
```ts
|
||||
import contents from "./file.txt";
|
||||
console.log(contents); // => "Hello, world!"
|
||||
|
||||
// To import an html file as text
|
||||
// The "type' attribute can be used to override the default loader.
|
||||
import html from "./index.html" with { type: "text" };
|
||||
```
|
||||
|
||||
When referenced during a build, the contents are inlined into the bundle as a string.
|
||||
|
||||
```ts
|
||||
var contents = `Hello, world!`;
|
||||
console.log(contents);
|
||||
```
|
||||
|
||||
If a `.txt` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the file contents.
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```txt#Input
|
||||
Hello, world!
|
||||
```
|
||||
|
||||
```js#Output
|
||||
export default "Hello, world!";
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
### `napi`
|
||||
|
||||
**Native addon loader**. Default for `.node`.
|
||||
|
||||
In the runtime, native addons can be directly imported.
|
||||
|
||||
```ts
|
||||
import addon from "./addon.node";
|
||||
console.log(addon);
|
||||
```
|
||||
|
||||
In the bundler, `.node` files are handled using the [`file`](#file) loader.
|
||||
|
||||
### `sqlite`
|
||||
|
||||
**SQLite loader**. `with { "type": "sqlite" }` import attribute
|
||||
|
||||
In the runtime and bundler, SQLite databases can be directly imported. This will load the database using [`bun:sqlite`](https://bun.com/docs/api/sqlite).
|
||||
|
||||
```ts
|
||||
import db from "./my.db" with { type: "sqlite" };
|
||||
```
|
||||
|
||||
This is only supported when the `target` is `bun`.
|
||||
|
||||
By default, the database is external to the bundle (so that you can potentially use a database loaded elsewhere), so the database file on-disk won't be bundled into the final output.
|
||||
|
||||
You can change this behavior with the `"embed"` attribute:
|
||||
|
||||
```ts
|
||||
// embed the database into the bundle
|
||||
import db from "./my.db" with { type: "sqlite", embed: "true" };
|
||||
```
|
||||
|
||||
When using a [standalone executable](https://bun.com/docs/bundler/executables), the database is embedded into the single-file executable.
|
||||
|
||||
Otherwise, the database to embed is copied into the `outdir` with a hashed filename.
|
||||
|
||||
### `html`
|
||||
|
||||
The html loader processes HTML files and bundles any referenced assets. It will:
|
||||
|
||||
- Bundle and hash referenced JavaScript files (`<script src="...">`)
|
||||
- Bundle and hash referenced CSS files (`<link rel="stylesheet" href="...">`)
|
||||
- Hash referenced images (`<img src="...">`)
|
||||
- Preserve external URLs (by default, anything starting with `http://` or `https://`)
|
||||
|
||||
For example, given this HTML file:
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```html#src/index.html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<img src="./image.jpg" alt="Local image">
|
||||
<img src="https://example.com/image.jpg" alt="External image">
|
||||
<script type="module" src="./script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
It will output a new HTML file with the bundled assets:
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```html#dist/output.html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<img src="./image-HASHED.jpg" alt="Local image">
|
||||
<img src="https://example.com/image.jpg" alt="External image">
|
||||
<script type="module" src="./output-ALSO-HASHED.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
Under the hood, it uses [`lol-html`](https://github.com/cloudflare/lol-html) to extract script and link tags as entrypoints, and other assets as external.
|
||||
|
||||
Currently, the list of selectors is:
|
||||
|
||||
- `audio[src]`
|
||||
- `iframe[src]`
|
||||
- `img[src]`
|
||||
- `img[srcset]`
|
||||
- `link:not([rel~='stylesheet']):not([rel~='modulepreload']):not([rel~='manifest']):not([rel~='icon']):not([rel~='apple-touch-icon'])[href]`
|
||||
- `link[as='font'][href], link[type^='font/'][href]`
|
||||
- `link[as='image'][href]`
|
||||
- `link[as='style'][href]`
|
||||
- `link[as='video'][href], link[as='audio'][href]`
|
||||
- `link[as='worker'][href]`
|
||||
- `link[rel='icon'][href], link[rel='apple-touch-icon'][href]`
|
||||
- `link[rel='manifest'][href]`
|
||||
- `link[rel='stylesheet'][href]`
|
||||
- `script[src]`
|
||||
- `source[src]`
|
||||
- `source[srcset]`
|
||||
- `video[poster]`
|
||||
- `video[src]`
|
||||
|
||||
{% callout %}
|
||||
|
||||
**HTML Loader Behavior in Different Contexts**
|
||||
|
||||
The `html` loader behaves differently depending on how it's used:
|
||||
|
||||
1. **Static Build:** When you run `bun build ./index.html`, Bun produces a static site with all assets bundled and hashed.
|
||||
|
||||
2. **Runtime:** When you run `bun run server.ts` (where `server.ts` imports an HTML file), Bun bundles assets on-the-fly during development, enabling features like hot module replacement.
|
||||
|
||||
3. **Full-stack Build:** When you run `bun build --target=bun server.ts` (where `server.ts` imports an HTML file), the import resolves to a manifest object that `Bun.serve` uses to efficiently serve pre-bundled assets in production.
|
||||
|
||||
{% /callout %}
|
||||
|
||||
### `sh` loader
|
||||
|
||||
**Bun Shell loader**. Default for `.sh` files
|
||||
|
||||
This loader is used to parse [Bun Shell](https://bun.com/docs/runtime/shell) scripts. It's only supported when starting Bun itself, so it's not available in the bundler or in the runtime.
|
||||
|
||||
```sh
|
||||
$ bun run ./script.sh
|
||||
```
|
||||
|
||||
### `file`
|
||||
|
||||
**File loader**. Default for all unrecognized file types.
|
||||
|
||||
The file loader resolves the import as a _path/URL_ to the imported file. It's commonly used for referencing media or font assets.
|
||||
|
||||
```ts#logo.ts
|
||||
import logo from "./logo.svg";
|
||||
console.log(logo);
|
||||
```
|
||||
|
||||
_In the runtime_, Bun checks that the `logo.svg` file exists and converts it to an absolute path to the location of `logo.svg` on disk.
|
||||
|
||||
```bash
|
||||
$ bun run logo.ts
|
||||
/path/to/project/logo.svg
|
||||
```
|
||||
|
||||
_In the bundler_, things are slightly different. The file is copied into `outdir` as-is, and the import is resolved as a relative path pointing to the copied file.
|
||||
|
||||
```ts#Output
|
||||
var logo = "./logo.svg";
|
||||
console.log(logo);
|
||||
```
|
||||
|
||||
If a value is specified for `publicPath`, the import will use value as a prefix to construct an absolute path/URL.
|
||||
|
||||
{% table %}
|
||||
|
||||
- Public path
|
||||
- Resolved import
|
||||
|
||||
---
|
||||
|
||||
- `""` (default)
|
||||
- `/logo.svg`
|
||||
|
||||
---
|
||||
|
||||
- `"/assets"`
|
||||
- `/assets/logo.svg`
|
||||
|
||||
---
|
||||
|
||||
- `"https://cdn.example.com/"`
|
||||
- `https://cdn.example.com/logo.svg`
|
||||
|
||||
{% /table %}
|
||||
|
||||
{% callout %}
|
||||
The location and file name of the copied file is determined by the value of [`naming.asset`](https://bun.com/docs/bundler#naming).
|
||||
{% /callout %}
|
||||
This loader is copied into the `outdir` as-is. The name of the copied file is determined using the value of `naming.asset`.
|
||||
|
||||
{% details summary="Fixing TypeScript import errors" %}
|
||||
If you're using TypeScript, you may get an error like this:
|
||||
|
||||
```ts
|
||||
// TypeScript error
|
||||
// Cannot find module './logo.svg' or its corresponding type declarations.
|
||||
```
|
||||
|
||||
This can be fixed by creating `*.d.ts` file anywhere in your project (any name will work) with the following contents:
|
||||
|
||||
```ts
|
||||
declare module "*.svg" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
```
|
||||
|
||||
This tells TypeScript that any default imports from `.svg` should be treated as a string.
|
||||
{% /details %}
|
||||
356
docs/bundler/loaders.mdx
Normal file
356
docs/bundler/loaders.mdx
Normal file
@@ -0,0 +1,356 @@
|
||||
---
|
||||
title: Loaders
|
||||
description: Built-in loaders for the Bun bundler and runtime
|
||||
---
|
||||
|
||||
The Bun bundler implements a set of default loaders out of the box.
|
||||
|
||||
> As a rule of thumb: **the bundler and the runtime both support the same set of file types out of the box.**
|
||||
|
||||
`.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` `.toml` `.json` `.txt` `.wasm` `.node` `.html`
|
||||
|
||||
Bun uses the file extension to determine which built-in loader should be used to parse the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building plugins that extend Bun with custom loaders.
|
||||
|
||||
You can explicitly specify which loader to use using the `'loader'` import attribute.
|
||||
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import my_toml from "./my_file" with { loader: "toml" };
|
||||
```
|
||||
|
||||
## Built-in loaders
|
||||
|
||||
### `js`
|
||||
|
||||
**JavaScript loader.** Default for `.cjs` and `.mjs`.
|
||||
|
||||
Parses the code and applies a set of default transforms like dead-code elimination and tree shaking. Note that Bun does not attempt to down-convert syntax at the moment.
|
||||
|
||||
---
|
||||
|
||||
### `jsx`
|
||||
|
||||
**JavaScript + JSX loader.** Default for `.js` and `.jsx`.
|
||||
|
||||
Same as the `js` loader, but JSX syntax is supported. By default, JSX is down-converted to plain JavaScript; the details of how this is done depends on the `jsx*` compiler options in your `tsconfig.json`. Refer to the [TypeScript documentation on JSX](https://www.typescriptlang.org/tsconfig#jsx) for more information.
|
||||
|
||||
---
|
||||
|
||||
### `ts`
|
||||
|
||||
**TypeScript loader.** Default for `.ts`, `.mts`, and `.cts`.
|
||||
|
||||
Strips out all TypeScript syntax, then behaves identically to the `js` loader. Bun does not perform typechecking.
|
||||
|
||||
---
|
||||
|
||||
### `tsx`
|
||||
|
||||
**TypeScript + JSX loader.** Default for `.tsx`.
|
||||
|
||||
Transpiles both TypeScript and JSX to vanilla JavaScript.
|
||||
|
||||
---
|
||||
|
||||
### `json`
|
||||
|
||||
**JSON loader.** Default for `.json`.
|
||||
|
||||
JSON files can be directly imported.
|
||||
|
||||
```js
|
||||
import pkg from "./package.json";
|
||||
pkg.name; // => "my-package"
|
||||
```
|
||||
|
||||
During bundling, the parsed JSON is inlined into the bundle as a JavaScript object.
|
||||
|
||||
```js
|
||||
const pkg = {
|
||||
name: "my-package",
|
||||
// ... other fields
|
||||
};
|
||||
|
||||
pkg.name;
|
||||
```
|
||||
|
||||
If a `.json` file is passed as an entrypoint to the bundler, it will be converted to a `.js` module that `export default`s the parsed object.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```json Input
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 35,
|
||||
"email": "johndoe@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
```ts Output
|
||||
export default {
|
||||
name: "John Doe",
|
||||
age: 35,
|
||||
email: "johndoe@example.com",
|
||||
};
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
---
|
||||
|
||||
### toml
|
||||
|
||||
**TOML loader.** Default for `.toml`.
|
||||
|
||||
TOML files can be directly imported. Bun will parse them with its fast native TOML parser.
|
||||
|
||||
```js
|
||||
import config from "./bunfig.toml";
|
||||
config.logLevel; // => "debug"
|
||||
|
||||
// via import attribute:
|
||||
// import myCustomTOML from './my.config' with {type: "toml"};
|
||||
```
|
||||
|
||||
During bundling, the parsed TOML is inlined into the bundle as a JavaScript object.
|
||||
|
||||
```js
|
||||
var config = {
|
||||
logLevel: "debug",
|
||||
// ...other fields
|
||||
};
|
||||
config.logLevel;
|
||||
```
|
||||
|
||||
If a `.toml` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the parsed object.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```toml Input
|
||||
name = "John Doe"
|
||||
age = 35
|
||||
email = "johndoe@example.com"
|
||||
```
|
||||
|
||||
```ts Output
|
||||
export default {
|
||||
name: "John Doe",
|
||||
age: 35,
|
||||
email: "johndoe@example.com",
|
||||
};
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
---
|
||||
|
||||
### text
|
||||
|
||||
**Text loader.** Default for `.txt`.
|
||||
|
||||
The contents of the text file are read and inlined into the bundle as a string. Text files can be directly imported. The file is read and returned as a string.
|
||||
|
||||
```js
|
||||
import contents from "./file.txt";
|
||||
console.log(contents); // => "Hello, world!"
|
||||
|
||||
// To import an html file as text
|
||||
// The "type" attribute can be used to override the default loader.
|
||||
import html from "./index.html" with { type: "text" };
|
||||
```
|
||||
|
||||
When referenced during a build, the contents are inlined into the bundle as a string.
|
||||
|
||||
```js
|
||||
var contents = `Hello, world!`;
|
||||
console.log(contents);
|
||||
```
|
||||
|
||||
If a `.txt` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the file contents.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```txt Input
|
||||
Hello, world!
|
||||
```
|
||||
|
||||
```ts Output
|
||||
export default "Hello, world!";
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
---
|
||||
|
||||
### napi
|
||||
|
||||
**Native addon loader.** Default for `.node`.
|
||||
|
||||
In the runtime, native addons can be directly imported.
|
||||
|
||||
```js
|
||||
import addon from "./addon.node";
|
||||
console.log(addon);
|
||||
```
|
||||
|
||||
<Note>In the bundler, `.node` files are handled using the file loader.</Note>
|
||||
|
||||
---
|
||||
|
||||
### sqlite
|
||||
|
||||
**SQLite loader.** Requires `with { "type": "sqlite" }` import attribute.
|
||||
|
||||
In the runtime and bundler, SQLite databases can be directly imported. This will load the database using `bun:sqlite`.
|
||||
|
||||
```js
|
||||
import db from "./my.db" with { type: "sqlite" };
|
||||
```
|
||||
|
||||
<Warning>This is only supported when the target is `bun`.</Warning>
|
||||
|
||||
By default, the database is external to the bundle (so that you can potentially use a database loaded elsewhere), so the database file on-disk won't be bundled into the final output.
|
||||
|
||||
You can change this behavior with the `"embed"` attribute:
|
||||
|
||||
```js
|
||||
// embed the database into the bundle
|
||||
import db from "./my.db" with { type: "sqlite", embed: "true" };
|
||||
```
|
||||
|
||||
<Info>
|
||||
When using a standalone executable, the database is embedded into the single-file executable.
|
||||
|
||||
Otherwise, the database to embed is copied into the `outdir` with a hashed filename.
|
||||
|
||||
</Info>
|
||||
|
||||
---
|
||||
|
||||
### html
|
||||
|
||||
The `html` loader processes HTML files and bundles any referenced assets. It will:
|
||||
|
||||
- Bundle and hash referenced JavaScript files (`<script src="...">`)
|
||||
- Bundle and hash referenced CSS files (`<link rel="stylesheet" href="...">`)
|
||||
- Hash referenced images (`<img src="...">`)
|
||||
- Preserve external URLs (by default, anything starting with `http://` or `https://`)
|
||||
|
||||
For example, given this HTML file:
|
||||
|
||||
```html title="src/index.html"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<img src="./image.jpg" alt="Local image" />
|
||||
<img src="https://example.com/image.jpg" alt="External image" />
|
||||
<script type="module" src="./script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
It will output a new HTML file with the bundled assets:
|
||||
|
||||
```html title="dist/index.html"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<img src="./image-HASHED.jpg" alt="Local image" />
|
||||
<img src="https://example.com/image.jpg" alt="External image" />
|
||||
<script type="module" src="./output-ALSO-HASHED.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Under the hood, it uses [`lol-html`](https://github.com/cloudflare/lol-html) to extract script and link tags as entrypoints, and other assets as external.
|
||||
|
||||
<Accordion title="List of supported HTML selectors">
|
||||
Currently, the list of selectors is:
|
||||
|
||||
- `audio[src]`
|
||||
- `iframe[src]`
|
||||
- `img[src]`
|
||||
- `img[srcset]`
|
||||
- `link:not([rel~='stylesheet']):not([rel~='modulepreload']):not([rel~='manifest']):not([rel~='icon']):not([rel~='apple-touch-icon'])[href]`
|
||||
- `link[as='font'][href], link[type^='font/'][href]`
|
||||
- `link[as='image'][href]`
|
||||
- `link[as='style'][href]`
|
||||
- `link[as='video'][href], link[as='audio'][href]`
|
||||
- `link[as='worker'][href]`
|
||||
- `link[rel='icon'][href], link[rel='apple-touch-icon'][href]`
|
||||
- `link[rel='manifest'][href]`
|
||||
- `link[rel='stylesheet'][href]`
|
||||
- `script[src]`
|
||||
- `source[src]`
|
||||
- `source[srcset]`
|
||||
- `video[poster]`
|
||||
- `video[src]`
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Note>
|
||||
|
||||
**HTML Loader Behavior in Different Contexts**
|
||||
|
||||
The `html` loader behaves differently depending on how it's used:
|
||||
|
||||
- Static Build: When you run `bun build ./index.html`, Bun produces a static site with all assets bundled and hashed.
|
||||
- Runtime: When you run `bun run server.ts` (where `server.ts` imports an HTML file), Bun bundles assets on-the-fly during development, enabling features like hot module replacement.
|
||||
- Full-stack Build: When you run `bun build --target=bun server.ts` (where `server.ts` imports an HTML file), the import resolves to a manifest object that `Bun.serve` uses to efficiently serve pre-bundled assets in production.
|
||||
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
### sh
|
||||
|
||||
**Bun Shell loader.** Default for `.sh` files.
|
||||
|
||||
This loader is used to parse Bun Shell scripts. It's only supported when starting Bun itself, so it's not available in the bundler or in the runtime.
|
||||
|
||||
```bash
|
||||
bun run ./script.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### file
|
||||
|
||||
**File loader.** Default for all unrecognized file types.
|
||||
|
||||
The file loader resolves the import as a path/URL to the imported file. It's commonly used for referencing media or font assets.
|
||||
|
||||
```js
|
||||
// logo.ts
|
||||
import logo from "./logo.svg";
|
||||
console.log(logo);
|
||||
```
|
||||
|
||||
In the runtime, Bun checks that the `logo.svg` file exists and converts it to an absolute path to the location of `logo.svg` on disk.
|
||||
|
||||
```bash
|
||||
bun run logo.ts
|
||||
# Output: /path/to/project/logo.svg
|
||||
```
|
||||
|
||||
In the bundler, things are slightly different. The file is copied into `outdir` as-is, and the import is resolved as a relative path pointing to the copied file.
|
||||
|
||||
```js
|
||||
// Output
|
||||
var logo = "./logo.svg";
|
||||
console.log(logo);
|
||||
```
|
||||
|
||||
If a value is specified for `publicPath`, the import will use value as a prefix to construct an absolute path/URL.
|
||||
|
||||
| Public path | Resolved import |
|
||||
| ---------------------------- | ---------------------------------- |
|
||||
| `""` (default) | `/logo.svg` |
|
||||
| `"/assets"` | `/assets/logo.svg` |
|
||||
| `"https://cdn.example.com/"` | `https://cdn.example.com/logo.svg` |
|
||||
|
||||
<Note>
|
||||
The location and file name of the copied file is determined by the value of `naming.asset`.
|
||||
|
||||
This loader is copied into the `outdir` as-is. The name of the copied file is determined using the value of `naming.asset`.
|
||||
|
||||
</Note>
|
||||
@@ -1,10 +1,13 @@
|
||||
Macros are a mechanism for running JavaScript functions _at bundle-time_. The value returned from these functions are directly inlined into your bundle.
|
||||
---
|
||||
title: Macros
|
||||
description: Run JavaScript functions at bundle-time with Bun macros
|
||||
---
|
||||
|
||||
<!-- embed the result in your (browser) bundle. This is useful for things like embedding the current Git commit hash in your code, making fetch requests to your API at build-time, dead code elimination, and more. -->
|
||||
Macros are a mechanism for running JavaScript functions at bundle-time. The value returned from these functions are directly inlined into your bundle.
|
||||
|
||||
As a toy example, consider this simple function that returns a random number.
|
||||
|
||||
```ts
|
||||
```ts title="random.ts" icon="/icons/typescript.svg"
|
||||
export function random() {
|
||||
return Math.random();
|
||||
}
|
||||
@@ -12,24 +15,28 @@ export function random() {
|
||||
|
||||
This is just a regular function in a regular file, but we can use it as a macro like so:
|
||||
|
||||
```ts#cli.tsx
|
||||
import { random } from './random.ts' with { type: 'macro' };
|
||||
```tsx title="cli.tsx" icon="/icons/typescript.svg"
|
||||
import { random } from "./random.ts" with { type: "macro" };
|
||||
|
||||
console.log(`Your random number is ${random()}`);
|
||||
```
|
||||
|
||||
{% callout %}
|
||||
**Note** — Macros are indicated using [_import attribute_](https://github.com/tc39/proposal-import-attributes) syntax. If you haven't seen this syntax before, it's a Stage 3 TC39 proposal that lets you attach additional metadata to `import` statements.
|
||||
{% /callout %}
|
||||
<Note>
|
||||
Macros are indicated using import attribute syntax. If you haven't seen this syntax before, it's a Stage 3 TC39
|
||||
proposal that lets you attach additional metadata to import statements.
|
||||
</Note>
|
||||
|
||||
Now we'll bundle this file with `bun build`. The bundled file will be printed to stdout.
|
||||
|
||||
```bash
|
||||
$ bun build ./cli.tsx
|
||||
```bash terminal icon="terminal"
|
||||
bun build ./cli.tsx
|
||||
```
|
||||
|
||||
```js
|
||||
console.log(`Your random number is ${0.6805550949689833}`);
|
||||
```
|
||||
|
||||
As you can see, the source code of the `random` function occurs nowhere in the bundle. Instead, it is executed _during bundling_ and function call (`random()`) is replaced with the result of the function. Since the source code will never be included in the bundle, macros can safely perform privileged operations like reading from a database.
|
||||
As you can see, the source code of the `random` function occurs nowhere in the bundle. Instead, it is executed during bundling and function call (`random()`) is replaced with the result of the function. Since the source code will never be included in the bundle, macros can safely perform privileged operations like reading from a database.
|
||||
|
||||
## When to use macros
|
||||
|
||||
@@ -41,8 +48,8 @@ If you find yourself running a lot of code at bundle-time though, consider runni
|
||||
|
||||
Bun Macros are import statements annotated using either:
|
||||
|
||||
- `with { type: 'macro' }` — an [import attribute](https://github.com/tc39/proposal-import-attributes), a Stage 3 ECMA Scrd
|
||||
- `assert { type: 'macro' }` — an import assertion, an earlier incarnation of import attributes that has now been abandoned (but is [already supported](https://caniuse.com/mdn-javascript_statements_import_import_assertions) by a number of browsers and runtimes)
|
||||
- `with { type: 'macro' }` — an import attribute, a Stage 3 ECMA Script proposal
|
||||
- `assert { type: 'macro' }` — an import assertion, an earlier incarnation of import attributes that has now been abandoned (but is already supported by a number of browsers and runtimes)
|
||||
|
||||
## Security considerations
|
||||
|
||||
@@ -50,7 +57,7 @@ Macros must explicitly be imported with `{ type: "macro" }` in order to be execu
|
||||
|
||||
You can disable macros entirely by passing the `--no-macros` flag to Bun. It produces a build error like this:
|
||||
|
||||
```js
|
||||
```
|
||||
error: Macros are disabled
|
||||
|
||||
foo();
|
||||
@@ -58,9 +65,9 @@ foo();
|
||||
./hello.js:3:1 53
|
||||
```
|
||||
|
||||
To reduce the potential attack surface for malicious packages, macros cannot be _invoked_ from inside `node_modules/**/*`. If a package attempts to invoke a macro, you'll see an error like this:
|
||||
To reduce the potential attack surface for malicious packages, macros cannot be invoked from inside `node_modules/**/*`. If a package attempts to invoke a macro, you'll see an error like this:
|
||||
|
||||
```js
|
||||
```
|
||||
error: For security reasons, macros cannot be run from node_modules.
|
||||
|
||||
beEvil();
|
||||
@@ -70,17 +77,17 @@ node_modules/evil/index.js:3:1 50
|
||||
|
||||
Your application code can still import macros from `node_modules` and invoke them.
|
||||
|
||||
```ts
|
||||
```ts title="cli.tsx" icon="/icons/typescript.svg"
|
||||
import { macro } from "some-package" with { type: "macro" };
|
||||
|
||||
macro();
|
||||
```
|
||||
|
||||
## Export condition `"macro"`
|
||||
## Export condition "macro"
|
||||
|
||||
When shipping a library containing a macro to `npm` or another package registry, use the `"macro"` [export condition](https://nodejs.org/api/packages.html#conditional-exports) to provide a special version of your package exclusively for the macro environment.
|
||||
When shipping a library containing a macro to npm or another package registry, use the `"macro"` export condition to provide a special version of your package exclusively for the macro environment.
|
||||
|
||||
```jsonc#package.json
|
||||
```json title="package.json" icon="file-code"
|
||||
{
|
||||
"name": "my-package",
|
||||
"exports": {
|
||||
@@ -94,7 +101,7 @@ When shipping a library containing a macro to `npm` or another package registry,
|
||||
|
||||
With this configuration, users can consume your package at runtime or at bundle-time using the same import specifier:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import pkg from "my-package"; // runtime import
|
||||
import { macro } from "my-package" with { type: "macro" }; // macro import
|
||||
```
|
||||
@@ -105,15 +112,15 @@ The first import will resolve to `./node_modules/my-package/index.js`, while the
|
||||
|
||||
When Bun's transpiler sees a macro import, it calls the function inside the transpiler using Bun's JavaScript runtime and converts the return value from JavaScript into an AST node. These JavaScript functions are called at bundle-time, not runtime.
|
||||
|
||||
Macros are executed synchronously in the transpiler during the visiting phase—before plugins and before the transpiler generates the AST. They are executed in the order they are imported. The transpiler will wait for the macro to finish executing before continuing. The transpiler will also `await` any `Promise` returned by a macro.
|
||||
Macros are executed synchronously in the transpiler during the visiting phase—before plugins and before the transpiler generates the AST. They are executed in the order they are imported. The transpiler will wait for the macro to finish executing before continuing. The transpiler will also await any Promise returned by a macro.
|
||||
|
||||
Bun's bundler is multi-threaded. As such, macros execute in parallel inside of multiple spawned JavaScript "workers".
|
||||
|
||||
## Dead code elimination
|
||||
|
||||
The bundler performs dead code elimination _after_ running and inlining macros. So given the following macro:
|
||||
The bundler performs dead code elimination after running and inlining macros. So given the following macro:
|
||||
|
||||
```ts#returnFalse.ts
|
||||
```ts title="returnFalse.ts" icon="/icons/typescript.svg"
|
||||
export function returnFalse() {
|
||||
return false;
|
||||
}
|
||||
@@ -121,7 +128,7 @@ export function returnFalse() {
|
||||
|
||||
...then bundling the following file will produce an empty bundle, provided that the minify syntax option is enabled.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { returnFalse } from "./returnFalse.ts" with { type: "macro" };
|
||||
|
||||
if (returnFalse()) {
|
||||
@@ -133,19 +140,19 @@ if (returnFalse()) {
|
||||
|
||||
Bun's transpiler needs to be able to serialize the result of the macro so it can be inlined into the AST. All JSON-compatible data structures are supported:
|
||||
|
||||
```ts#macro.ts
|
||||
```ts title="macro.ts" icon="/icons/typescript.svg"
|
||||
export function getObject() {
|
||||
return {
|
||||
foo: "bar",
|
||||
baz: 123,
|
||||
array: [ 1, 2, { nested: "value" }],
|
||||
array: [1, 2, { nested: "value" }],
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Macros can be async, or return `Promise` instances. Bun's transpiler will automatically `await` the `Promise` and inline the result.
|
||||
Macros can be async, or return Promise instances. Bun's transpiler will automatically await the Promise and inline the result.
|
||||
|
||||
```ts#macro.ts
|
||||
```ts title="macro.ts" icon="/icons/typescript.svg"
|
||||
export async function getText() {
|
||||
return "async value";
|
||||
}
|
||||
@@ -153,21 +160,21 @@ export async function getText() {
|
||||
|
||||
The transpiler implements special logic for serializing common data formats like `Response`, `Blob`, `TypedArray`.
|
||||
|
||||
- `TypedArray`: Resolves to a base64-encoded string.
|
||||
- `Response`: Bun will read the `Content-Type` and serialize accordingly; for instance, a `Response` with type `application/json` will be automatically parsed into an object and `text/plain` will be inlined as a string. Responses with an unrecognized or `undefined` `type` will be base-64 encoded.
|
||||
- `Blob`: As with `Response`, the serialization depends on the `type` property.
|
||||
- **TypedArray**: Resolves to a base64-encoded string.
|
||||
- **Response**: Bun will read the `Content-Type` and serialize accordingly; for instance, a Response with type `application/json` will be automatically parsed into an object and `text/plain` will be inlined as a string. Responses with an unrecognized or undefined type will be base-64 encoded.
|
||||
- **Blob**: As with Response, the serialization depends on the `type` property.
|
||||
|
||||
The result of `fetch` is `Promise<Response>`, so it can be directly returned.
|
||||
|
||||
```ts#macro.ts
|
||||
```ts title="macro.ts" icon="/icons/typescript.svg"
|
||||
export function getObject() {
|
||||
return fetch("https://bun.com")
|
||||
return fetch("https://bun.com");
|
||||
}
|
||||
```
|
||||
|
||||
Functions and instances of most classes (except those mentioned above) are not serializable.
|
||||
|
||||
```ts
|
||||
```ts title="macro.ts" icon="/icons/typescript.svg"
|
||||
export function getText(url: string) {
|
||||
// this doesn't work!
|
||||
return () => {};
|
||||
@@ -178,7 +185,7 @@ export function getText(url: string) {
|
||||
|
||||
Macros can accept inputs, but only in limited cases. The value must be statically known. For example, the following is not allowed:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { getText } from "./getText.ts" with { type: "macro" };
|
||||
|
||||
export function howLong() {
|
||||
@@ -192,7 +199,7 @@ export function howLong() {
|
||||
|
||||
However, if the value of `foo` is known at bundle-time (say, if it's a constant or the result of another macro) then it's allowed:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { getText } from "./getText.ts" with { type: "macro" };
|
||||
import { getFoo } from "./getFoo.ts" with { type: "macro" };
|
||||
|
||||
@@ -206,7 +213,7 @@ export function howLong() {
|
||||
|
||||
This outputs:
|
||||
|
||||
```ts
|
||||
```js
|
||||
function howLong() {
|
||||
console.log("The page is", 1322, "characters long");
|
||||
}
|
||||
@@ -217,11 +224,9 @@ export { howLong };
|
||||
|
||||
### Embed latest git commit hash
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```ts#getGitCommitHash.ts
|
||||
```ts title="getGitCommitHash.ts" icon="/icons/typescript.svg"
|
||||
export function getGitCommitHash() {
|
||||
const {stdout} = Bun.spawnSync({
|
||||
const { stdout } = Bun.spawnSync({
|
||||
cmd: ["git", "rev-parse", "HEAD"],
|
||||
stdout: "pipe",
|
||||
});
|
||||
@@ -230,33 +235,32 @@ export function getGitCommitHash() {
|
||||
}
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
<!-- --target=browser so they can clearly see it's for browsers -->
|
||||
|
||||
When we build it, the `getGitCommitHash` is replaced with the result of calling the function:
|
||||
|
||||
{% codetabs %}
|
||||
<CodeGroup>
|
||||
|
||||
```ts#input
|
||||
import { getGitCommitHash } from './getGitCommitHash.ts' with { type: 'macro' };
|
||||
```ts input
|
||||
import { getGitCommitHash } from "./getGitCommitHash.ts" with { type: "macro" };
|
||||
|
||||
console.log(`The current Git commit hash is ${getGitCommitHash()}`);
|
||||
```
|
||||
|
||||
```bash#output
|
||||
console.log(`The current Git commit hash is 3ee3259104f`);
|
||||
```ts output
|
||||
console.log(`The current Git commit hash is 3ee3259104e4507cf62c160f0ff5357ec4c7a7f8`);
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
</CodeGroup>
|
||||
|
||||
You're probably thinking "Why not just use `process.env.GIT_COMMIT_HASH`?" Well, you can do that too. But can you do this with an environment variable?
|
||||
<Info>
|
||||
You're probably thinking "Why not just use `process.env.GIT_COMMIT_HASH`?" Well, you can do that too. But can you do
|
||||
this with an environment variable?
|
||||
</Info>
|
||||
|
||||
### Make `fetch()` requests at bundle-time
|
||||
### Make fetch() requests at bundle-time
|
||||
|
||||
In this example, we make an outgoing HTTP request using `fetch()`, parse the HTML response using `HTMLRewriter`, and return an object containing the title and meta tags–all at bundle-time.
|
||||
|
||||
```ts
|
||||
```ts title="meta.ts" icon="/icons/typescript.svg"
|
||||
export async function extractMetaTags(url: string) {
|
||||
const response = await fetch(url);
|
||||
const meta = {
|
||||
@@ -271,9 +275,7 @@ export async function extractMetaTags(url: string) {
|
||||
.on("meta", {
|
||||
element(element) {
|
||||
const name =
|
||||
element.getAttribute("name") ||
|
||||
element.getAttribute("property") ||
|
||||
element.getAttribute("itemprop");
|
||||
element.getAttribute("name") || element.getAttribute("property") || element.getAttribute("itemprop");
|
||||
|
||||
if (name) meta[name] = element.getAttribute("content");
|
||||
},
|
||||
@@ -284,14 +286,12 @@ export async function extractMetaTags(url: string) {
|
||||
}
|
||||
```
|
||||
|
||||
<!-- --target=browser so they can clearly see it's for browsers -->
|
||||
The `extractMetaTags` function is erased at bundle-time and replaced with the result of the function call. This means that the fetch request happens at bundle-time, and the result is embedded in the bundle. Also, the branch throwing the error is eliminated since it's unreachable.
|
||||
|
||||
The `extractMetaTags` function is erased at bundle-time and replaced with the result of the function call. This means that the `fetch` request happens at bundle-time, and the result is embedded in the bundle. Also, the branch throwing the error is eliminated since it's unreachable.
|
||||
<CodeGroup>
|
||||
|
||||
{% codetabs %}
|
||||
|
||||
```ts#input
|
||||
import { extractMetaTags } from './meta.ts' with { type: 'macro' };
|
||||
```jsx input
|
||||
import { extractMetaTags } from "./meta.ts" with { type: "macro" };
|
||||
|
||||
export const Head = () => {
|
||||
const headTags = extractMetaTags("https://example.com");
|
||||
@@ -300,30 +300,29 @@ export const Head = () => {
|
||||
throw new Error("Expected title to be 'Example Domain'");
|
||||
}
|
||||
|
||||
return <head>
|
||||
<title>{headTags.title}</title>
|
||||
<meta name="viewport" content={headTags.viewport} />
|
||||
</head>;
|
||||
return (
|
||||
<head>
|
||||
<title>{headTags.title}</title>
|
||||
<meta name="viewport" content={headTags.viewport} />
|
||||
</head>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
```ts#output
|
||||
import { jsx, jsxs } from "react/jsx-runtime";
|
||||
```jsx output
|
||||
export const Head = () => {
|
||||
jsxs("head", {
|
||||
children: [
|
||||
jsx("title", {
|
||||
children: "Example Domain",
|
||||
}),
|
||||
jsx("meta", {
|
||||
name: "viewport",
|
||||
content: "width=device-width, initial-scale=1",
|
||||
}),
|
||||
],
|
||||
});
|
||||
};
|
||||
const headTags = {
|
||||
title: "Example Domain",
|
||||
viewport: "width=device-width, initial-scale=1",
|
||||
};
|
||||
|
||||
export { Head };
|
||||
return (
|
||||
<head>
|
||||
<title>{headTags.title}</title>
|
||||
<meta name="viewport" content={headTags.viewport} />
|
||||
</head>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
</CodeGroup>
|
||||
1306
docs/bundler/minifier.mdx
Normal file
1306
docs/bundler/minifier.mdx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,9 @@
|
||||
Bun provides a universal plugin API that can be used to extend both the _runtime_ and _bundler_.
|
||||
---
|
||||
title: Plugins
|
||||
description: Universal plugin API for extending Bun's runtime and bundler
|
||||
---
|
||||
|
||||
Bun provides a universal plugin API that can be used to extend both the runtime and bundler.
|
||||
|
||||
Plugins intercept imports and perform custom loading logic: reading files, transpiling code, etc. They can be used to add support for additional file types, like `.scss` or `.yaml`. In the context of Bun's bundler, plugins can be used to implement framework-level features like CSS extraction, macros, and client-server code co-location.
|
||||
|
||||
@@ -6,20 +11,18 @@ Plugins intercept imports and perform custom loading logic: reading files, trans
|
||||
|
||||
Plugins can register callbacks to be run at various points in the lifecycle of a bundle:
|
||||
|
||||
- [`onStart()`](#onstart): Run once the bundler has started a bundle
|
||||
- [`onResolve()`](#onresolve): Run before a module is resolved
|
||||
- [`onLoad()`](#onload): Run before a module is loaded.
|
||||
- [`onEnd()`](#onend): Run after the bundle has completed
|
||||
- [`onBeforeParse()`](#onbeforeparse): Run zero-copy native addons in the parser thread before a file is parsed.
|
||||
- `onStart()`: Run once the bundler has started a bundle
|
||||
- `onResolve()`: Run before a module is resolved
|
||||
- `onLoad()`: Run before a module is loaded
|
||||
- `onBeforeParse()`: Run zero-copy native addons in the parser thread before a file is parsed
|
||||
|
||||
### Reference
|
||||
## Reference
|
||||
|
||||
A rough overview of the types (please refer to Bun's `bun.d.ts` for the full type definitions):
|
||||
|
||||
```ts
|
||||
```ts title="bun.d.ts" icon="/icons/typescript.svg"
|
||||
type PluginBuilder = {
|
||||
onStart(callback: () => void): void;
|
||||
onEnd(callback: (result: BuildOutput) => void | Promise<void>): void;
|
||||
onResolve: (
|
||||
args: { filter: RegExp; namespace?: string },
|
||||
callback: (args: { path: string; importer: string }) => {
|
||||
@@ -46,7 +49,7 @@ type Loader = "js" | "jsx" | "ts" | "tsx" | "css" | "json" | "toml";
|
||||
|
||||
A plugin is defined as simple JavaScript object containing a `name` property and a `setup` function.
|
||||
|
||||
```tsx#myPlugin.ts
|
||||
```ts title="myPlugin.ts" icon="/icons/typescript.svg"
|
||||
import type { BunPlugin } from "bun";
|
||||
|
||||
const myPlugin: BunPlugin = {
|
||||
@@ -59,7 +62,7 @@ const myPlugin: BunPlugin = {
|
||||
|
||||
This plugin can be passed into the `plugins` array when calling `Bun.build`.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
await Bun.build({
|
||||
entrypoints: ["./app.ts"],
|
||||
outdir: "./out",
|
||||
@@ -82,7 +85,7 @@ Other common namespaces are:
|
||||
- `"bun"`: for Bun-specific modules (e.g. `"bun:test"`, `"bun:sqlite"`)
|
||||
- `"node"`: for Node.js modules (e.g. `"node:fs"`, `"node:path"`)
|
||||
|
||||
### `onStart`
|
||||
### onStart
|
||||
|
||||
```ts
|
||||
onStart(callback: () => void): Promise<void> | void;
|
||||
@@ -90,7 +93,7 @@ onStart(callback: () => void): Promise<void> | void;
|
||||
|
||||
Registers a callback to be run when the bundler starts a new bundle.
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { plugin } from "bun";
|
||||
|
||||
plugin({
|
||||
@@ -104,11 +107,11 @@ plugin({
|
||||
});
|
||||
```
|
||||
|
||||
The callback can return a `Promise`. After the bundle process has initialized, the bundler waits until all `onStart()` callbacks have completed before continuing.
|
||||
The callback can return a Promise. After the bundle process has initialized, the bundler waits until all `onStart()` callbacks have completed before continuing.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
const result = await Bun.build({
|
||||
entrypoints: ["./app.ts"],
|
||||
outdir: "./dist",
|
||||
@@ -118,7 +121,7 @@ const result = await Bun.build({
|
||||
name: "Sleep for 10 seconds",
|
||||
setup(build) {
|
||||
build.onStart(async () => {
|
||||
await Bunlog.sleep(10_000);
|
||||
await Bun.sleep(10_000);
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -135,11 +138,14 @@ const result = await Bun.build({
|
||||
});
|
||||
```
|
||||
|
||||
In the above example, Bun will wait until the first `onStart()` (sleeping for 10 seconds) has completed, _as well as_ the second `onStart()` (writing the bundle time to a file).
|
||||
In the above example, Bun will wait until the first `onStart()` (sleeping for 10 seconds) has completed, as well as the second `onStart()` (writing the bundle time to a file).
|
||||
|
||||
Note that `onStart()` callbacks (like every other lifecycle callback) do not have the ability to modify the `build.config` object. If you want to mutate `build.config`, you must do so directly in the `setup()` function.
|
||||
<Note>
|
||||
`onStart()` callbacks (like every other lifecycle callback) do not have the ability to modify the `build.config`
|
||||
object. If you want to mutate `build.config`, you must do so directly in the `setup()` function.
|
||||
</Note>
|
||||
|
||||
### `onResolve`
|
||||
### onResolve
|
||||
|
||||
```ts
|
||||
onResolve(
|
||||
@@ -155,15 +161,15 @@ To bundle your project, Bun walks down the dependency tree of all modules in you
|
||||
|
||||
The `onResolve()` plugin lifecycle callback allows you to configure how a module is resolved.
|
||||
|
||||
The first argument to `onResolve()` is an object with a `filter` and [`namespace`](#what-is-a-namespace) property. The filter is a regular expression which is run on the import string. Effectively, these allow you to filter which modules your custom resolution logic will apply to.
|
||||
The first argument to `onResolve()` is an object with a `filter` and `namespace` property. The `filter` is a regular expression which is run on the import string. Effectively, these allow you to filter which modules your custom resolution logic will apply to.
|
||||
|
||||
The second argument to `onResolve()` is a callback which is run for each module import Bun finds that matches the `filter` and `namespace` defined in the first argument.
|
||||
The second argument to `onResolve()` is a callback which is run for each module import Bun finds that matches the filter and namespace defined in the first argument.
|
||||
|
||||
The callback receives as input the _path_ to the matching module. The callback can return a _new path_ for the module. Bun will read the contents of the _new path_ and parse it as a module.
|
||||
The callback receives as input the path to the matching module. The callback can return a new path for the module. Bun will read the contents of the new path and parse it as a module.
|
||||
|
||||
For example, redirecting all imports to `images/` to `./public/images/`:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { plugin } from "bun";
|
||||
|
||||
plugin({
|
||||
@@ -180,7 +186,7 @@ plugin({
|
||||
});
|
||||
```
|
||||
|
||||
### `onLoad`
|
||||
### onLoad
|
||||
|
||||
```ts
|
||||
onLoad(
|
||||
@@ -196,19 +202,19 @@ onLoad(
|
||||
|
||||
After Bun's bundler has resolved a module, it needs to read the contents of the module and parse it.
|
||||
|
||||
The `onLoad()` plugin lifecycle callback allows you to modify the _contents_ of a module before it is read and parsed by Bun.
|
||||
The `onLoad()` plugin lifecycle callback allows you to modify the contents of a module before it is read and parsed by Bun.
|
||||
|
||||
Like `onResolve()`, the first argument to `onLoad()` allows you to filter which modules this invocation of `onLoad()` will apply to.
|
||||
|
||||
The second argument to `onLoad()` is a callback which is run for each matching module _before_ Bun loads the contents of the module into memory.
|
||||
The second argument to `onLoad()` is a callback which is run for each matching module before Bun loads the contents of the module into memory.
|
||||
|
||||
This callback receives as input the _path_ to the matching module, the _importer_ of the module (the module that imported the module), the _namespace_ of the module, and the _kind_ of the module.
|
||||
This callback receives as input the path to the matching module, the importer of the module (the module that imported the module), the namespace of the module, and the kind of the module.
|
||||
|
||||
The callback can return a new `contents` string for the module as well as a new `loader`.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { plugin } from "bun";
|
||||
|
||||
const envPlugin: BunPlugin = {
|
||||
@@ -235,17 +241,17 @@ Bun.build({
|
||||
|
||||
This plugin will transform all imports of the form `import env from "env"` into a JavaScript module that exports the current environment variables.
|
||||
|
||||
#### `.defer()`
|
||||
#### .defer()
|
||||
|
||||
One of the arguments passed to the `onLoad` callback is a `defer` function. This function returns a `Promise` that is resolved when all _other_ modules have been loaded.
|
||||
One of the arguments passed to the `onLoad` callback is a `defer` function. This function returns a Promise that is resolved when all other modules have been loaded.
|
||||
|
||||
This allows you to delay execution of the `onLoad` callback until all other modules have been loaded.
|
||||
|
||||
This is useful for returning contents of a module that depends on other modules.
|
||||
|
||||
##### Example: tracking and reporting unused exports
|
||||
<Accordion title="Example: tracking and reporting unused exports">
|
||||
|
||||
```ts
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import { plugin } from "bun";
|
||||
|
||||
plugin({
|
||||
@@ -285,54 +291,11 @@ plugin({
|
||||
});
|
||||
```
|
||||
|
||||
Note that the `.defer()` function currently has the limitation that it can only be called once per `onLoad` callback.
|
||||
</Accordion>
|
||||
|
||||
### `onEnd`
|
||||
|
||||
```ts
|
||||
onEnd(callback: (result: BuildOutput) => void | Promise<void>): void;
|
||||
```
|
||||
|
||||
Registers a callback to be run when the bundler completes a bundle (whether successful or not).
|
||||
|
||||
The callback receives the `BuildOutput` object containing:
|
||||
|
||||
- `success`: boolean indicating if the build succeeded
|
||||
- `outputs`: array of generated build artifacts
|
||||
- `logs`: array of build messages (warnings, errors, etc.)
|
||||
|
||||
This is useful for post-processing, cleanup, notifications, or custom error handling.
|
||||
|
||||
```ts
|
||||
await Bun.build({
|
||||
entrypoints: ["./index.ts"],
|
||||
outdir: "./out",
|
||||
plugins: [
|
||||
{
|
||||
name: "onEnd example",
|
||||
setup(build) {
|
||||
build.onEnd(result => {
|
||||
if (result.success) {
|
||||
console.log(
|
||||
`✅ Build succeeded with ${result.outputs.length} outputs`,
|
||||
);
|
||||
} else {
|
||||
console.error(`❌ Build failed with ${result.logs.length} errors`);
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The `onEnd` callbacks are called:
|
||||
|
||||
- **Before** the build promise resolves or rejects
|
||||
- **After** all bundling is complete
|
||||
- **In the order** they were registered
|
||||
|
||||
Multiple plugins can register `onEnd` callbacks, and they will all be called sequentially. If an `onEnd` callback returns a promise, the build will wait for it to resolve before continuing.
|
||||
<Warning>
|
||||
The `.defer()` function currently has the limitation that it can only be called once per `onLoad` callback.
|
||||
</Warning>
|
||||
|
||||
## Native plugins
|
||||
|
||||
@@ -340,13 +303,13 @@ One of the reasons why Bun's bundler is so fast is that it is written in native
|
||||
|
||||
However, one limitation of plugins written in JavaScript is that JavaScript itself is single-threaded.
|
||||
|
||||
Native plugins are written as [NAPI](https://bun.com/docs/api/node-api) modules and can be run on multiple threads. This allows native plugins to run much faster than JavaScript plugins.
|
||||
Native plugins are written as NAPI modules and can be run on multiple threads. This allows native plugins to run much faster than JavaScript plugins.
|
||||
|
||||
In addition, native plugins can skip unnecessary work such as the UTF-8 -> UTF-16 conversion needed to pass strings to JavaScript.
|
||||
|
||||
These are the following lifecycle hooks which are available to native plugins:
|
||||
|
||||
- [`onBeforeParse()`](#onbeforeparse): Called on any thread before a file is parsed by Bun's bundler.
|
||||
- `onBeforeParse()`: Called on any thread before a file is parsed by Bun's bundler.
|
||||
|
||||
Native plugins are NAPI modules which expose lifecycle hooks as C ABI functions.
|
||||
|
||||
@@ -358,23 +321,22 @@ Native plugins are NAPI modules which expose lifecycle hooks as C ABI functions.
|
||||
|
||||
To create a native plugin, you must export a C ABI function which matches the signature of the native lifecycle hook you want to implement.
|
||||
|
||||
```bash
|
||||
```bash terminal icon="terminal"
|
||||
bun add -g @napi-rs/cli
|
||||
napi new
|
||||
```
|
||||
|
||||
Then install this crate:
|
||||
|
||||
```bash
|
||||
```bash terminal icon="terminal"
|
||||
cargo add bun-native-plugin
|
||||
```
|
||||
|
||||
Now, inside the `lib.rs` file, we'll use the `bun_native_plugin::bun` proc macro to define a function which
|
||||
will implement our native plugin.
|
||||
Now, inside the `lib.rs` file, we'll use the `bun_native_plugin::bun` proc macro to define a function which will implement our native plugin.
|
||||
|
||||
Here's an example implementing the `onBeforeParse` hook:
|
||||
|
||||
```rs
|
||||
```rust title="lib.rs" icon="/icons/rust.svg"
|
||||
use bun_native_plugin::{define_bun_plugin, OnBeforeParse, bun, Result, anyhow, BunLoader};
|
||||
use napi_derive::napi;
|
||||
|
||||
@@ -396,7 +358,6 @@ pub fn replace_foo_with_bar(handle: &mut OnBeforeParse) -> Result<()> {
|
||||
// Get the Loader for the file
|
||||
let loader = handle.output_loader();
|
||||
|
||||
|
||||
let output_source_code = input_source_code.replace("foo", "bar");
|
||||
|
||||
handle.set_output_source_code(output_source_code, BunLoader::BUN_LOADER_JSX);
|
||||
@@ -405,10 +366,11 @@ pub fn replace_foo_with_bar(handle: &mut OnBeforeParse) -> Result<()> {
|
||||
}
|
||||
```
|
||||
|
||||
And to use it in Bun.build():
|
||||
And to use it in `Bun.build()`:
|
||||
|
||||
```typescript
|
||||
```ts title="index.ts" icon="/icons/typescript.svg"
|
||||
import myNativeAddon from "./my-native-addon";
|
||||
|
||||
Bun.build({
|
||||
entrypoints: ["./app.tsx"],
|
||||
plugins: [
|
||||
@@ -433,7 +395,7 @@ Bun.build({
|
||||
});
|
||||
```
|
||||
|
||||
### `onBeforeParse`
|
||||
### onBeforeParse
|
||||
|
||||
```ts
|
||||
onBeforeParse(
|
||||
@@ -446,4 +408,4 @@ This lifecycle callback is run immediately before a file is parsed by Bun's bund
|
||||
|
||||
As input, it receives the file's contents and can optionally return new source code.
|
||||
|
||||
This callback can be called from any thread and so the napi module implementation must be thread-safe.
|
||||
<Info>This callback can be called from any thread and so the napi module implementation must be thread-safe.</Info>
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user