---
name: bun-bundler-489bbd06279a
user-invocable: false
description: Use when bundling JavaScript/TypeScript code with Bun's fast bundler. Covers building for different targets, tree-shaking, code splitting, and optimization strategies.
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Grep
  - Glob
---

# Bun Bundler

Use this skill when bundling JavaScript/TypeScript applications with Bun's built-in bundler, which provides exceptional performance and modern features.

## Key Concepts

### Basic Bundling

Bun can bundle your code for different targets:

```bash
# Bundle for Bun runtime
bun build ./src/index.ts --outdir ./dist

# Bundle for browsers
bun build ./src/index.ts --outdir ./dist --target=browser

# Bundle for Node.js
bun build ./src/index.ts --outdir ./dist --target=node

# Minify output
bun build ./src/index.ts --outdir ./dist --minify
```

### Programmatic API

Use Bun's build API in TypeScript:

```typescript
import { build } from "bun";

await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  target: "bun",
  minify: true,
  sourcemap: "external",
});
```

### Build Targets

Bun supports multiple build targets:

- `bun` - Optimized for Bun runtime (default)
- `browser` - Browser-compatible bundle
- `node` - Node.js-compatible bundle

### Output Formats

Control output format:

```typescript
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  format: "esm", // or "cjs", "iife"
});
```

## Best Practices

### Entry Points Configuration

Define multiple entry points for complex applications:

```typescript
await build({
  entrypoints: [
    "./src/client/index.ts",
    "./src/server/index.ts",
    "./src/worker.ts",
  ],
  outdir: "./dist",
  naming: {
    entry: "[dir]/[name].[ext]",
    chunk: "[name]-[hash].[ext]",
    asset: "assets/[name]-[hash].[ext]",
  },
});
```

### Tree Shaking

Bun automatically tree-shakes unused code:

```typescript
// utils.ts
export function used() {
  return "used";
}

export function unused() {
  return "unused";
}

// index.ts
import { used } from "./utils";

console.log(used()); // Only 'used' function will be bundled
```

### Code Splitting

Split code for better loading performance:

```typescript
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  splitting: true, // Enable code splitting
  target: "browser",
});
```

### Environment Variables

Replace environment variables at build time:

```typescript
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  define: {
    "process.env.API_URL": JSON.stringify("https://api.example.com"),
    "process.env.NODE_ENV": JSON.stringify("production"),
  },
});
```

### External Dependencies

Mark dependencies as external to exclude from bundle:

```typescript
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  external: ["react", "react-dom"], // Don't bundle React
  target: "browser",
});
```

### Source Maps

Generate source maps for debugging:

```typescript
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  sourcemap: "external", // or "inline", "none"
  minify: true,
});
```

## Common Patterns

### Building a Library

```typescript
// build.ts
import { build } from "bun";

// ESM build
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist/esm",
  format: "esm",
  target: "node",
  minify: true,
  sourcemap: "external",
});

// CJS build
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist/cjs",
  format: "cjs",
  target: "node",
  minify: true,
  sourcemap: "external",
});

console.log("Build complete!");
```

### Building a Web Application

```typescript
// build.ts
import { build } from "bun";

await build({
  entrypoints: ["./src/index.tsx"],
  outdir: "./dist",
  target: "browser",
  format: "esm",
  minify: true,
  splitting: true,
  sourcemap: "external",
  publicPath: "/assets/",
  naming: {
    entry: "[dir]/[name].[ext]",
    chunk: "[name]-[hash].[ext]",
    asset: "assets/[name]-[hash].[ext]",
  },
  define: {
    "process.env.NODE_ENV": JSON.stringify("production"),
  },
});
```

### Building Multiple Outputs

```typescript
// build.ts
import { build } from "bun";

const builds = [
  {
    entrypoints: ["./src/index.ts"],
    outdir: "./dist/esm",
    format: "esm" as const,
    target: "browser" as const,
  },
  {
    entrypoints: ["./src/index.ts"],
    outdir: "./dist/cjs",
    format: "cjs" as const,
    target: "node" as const,
  },
  {
    entrypoints: ["./src/index.ts"],
    outdir: "./dist/iife",
    format: "iife" as const,
    target: "browser" as const,
  },
];

for (const config of builds) {
  await build({
    ...config,
    minify: true,
    sourcemap: "external",
  });
}

console.log("All builds complete!");
```

### Build Script with Watching

```typescript
// watch-build.ts
import { watch } from "fs";
import { build } from "bun";

async function buildApp() {
  console.log("Building...");
  await build({
    entrypoints: ["./src/index.ts"],
    outdir: "./dist",
    target: "bun",
  });
  console.log("Build complete!");
}

// Initial build
await buildApp();

// Watch for changes
watch("./src", { recursive: true }, async (event, filename) => {
  console.log(`File changed: ${filename}`);
  await buildApp();
});
```

### Plugin System

Create custom build plugins:

```typescript
import type { BunPlugin } from "bun";

const myPlugin: BunPlugin = {
  name: "my-plugin",
  setup(build) {
    build.onLoad({ filter: /\.custom$/ }, async (args) => {
      const text = await Bun.file(args.path).text();
      return {
        contents: `export default ${JSON.stringify(text)}`,
        loader: "js",
      };
    });
  },
};

await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  plugins: [myPlugin],
});
```

## Anti-Patterns

### Don't Bundle Node Modules for Node Target

```typescript
// Bad - Bundling all dependencies for Node
await build({
  entrypoints: ["./src/server.ts"],
  target: "node",
  // Missing external configuration
});

// Good - Mark dependencies as external
await build({
  entrypoints: ["./src/server.ts"],
  target: "node",
  external: ["express", "mongoose", "*"], // "*" excludes all node_modules
});
```

### Don't Ignore Build Errors

```typescript
// Bad - No error handling
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
});

// Good - Handle build errors
try {
  const result = await build({
    entrypoints: ["./src/index.ts"],
    outdir: "./dist",
  });

  if (!result.success) {
    console.error("Build failed");
    process.exit(1);
  }

  console.log("Build succeeded");
} catch (error) {
  console.error("Build error:", error);
  process.exit(1);
}
```

### Don't Minify Development Builds

```typescript
// Bad - Always minifying
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  minify: true, // Hard to debug in development
});

// Good - Conditional minification
const isDev = Bun.env.NODE_ENV === "development";

await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  minify: !isDev,
  sourcemap: isDev ? "inline" : "external",
});
```

### Don't Over-Split Code

```typescript
// Bad - Excessive code splitting
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  splitting: true,
  target: "bun", // Code splitting not needed for Bun target
});

// Good - Split only when beneficial
await build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  splitting: true,
  target: "browser", // Beneficial for browsers
});
```

## Related Skills

- **bun-runtime**: Understanding Bun's runtime for target optimization
- **bun-package-manager**: Managing build dependencies
- **bun-testing**: Testing bundled code


---
Source attribution: TheBushidoCollective
Original project: https://github.com/TheBushidoCollective/han/blob/19caa51d5fd144ef6b2764f2332f4c856aa5d1af/plugins/tools/bun/skills/bun-bundler/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

# Functional Source License, Version 1.1, ALv2 Future License

## Abbreviation

FSL-1.1-ALv2

## Notice

Copyright 2025 The Bushido Collective

## Terms and Conditions

### Licensor ("We")

The party offering the Software under these Terms and Conditions.

### The Software

The "Software" is each version of the software that we make available under
these Terms and Conditions, as indicated by our inclusion of these Terms and
Conditions with the Software.

### License Grant

Subject to your compliance with this License Grant and the Patents,
Redistribution and Trademark clauses below, we hereby grant you the right to
use, copy, modify, create derivative works, publicly perform, publicly display
and redistribute the Software for any Permitted Purpose identified below.

### Permitted Purpose

A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
means making the Software available to others in a commercial product or
service that:

1. substitutes for the Software;

2. substitutes for any other product or service we offer using the Software
   that exists as of the date we make the Software available; or

3. offers the same or substantially similar functionality as the Software.

Permitted Purposes specifically include using the Software:

1. for your internal use and access;

2. for non-commercial education;

3. for non-commercial research; and

4. in connection with professional services that you provide to a licensee
   using the Software in accordance with these Terms and Conditions.

### Patents

To the extent your use for a Permitted Purpose would necessarily infringe our
patents, the license grant above includes a license under our patents. If you
make a claim against any party that the Software infringes or contributes to
the infringement of any patent, then your patent license to the Software ends
immediately.

### Redistribution

The Terms and Conditions apply to all copies, modifications and derivatives of
the Software.

If you redistribute any copies, modifications or derivatives of the Software,
you must include a copy of or a link to these Terms and Conditions and not
remove any copyright notices provided in or with the Software.

### Disclaimer

THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.

IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.

### Trademarks

Except for displaying the License Details and identifying us as the origin of
the Software, you have no right under these Terms and Conditions to use our
trademarks, trade names, service marks or product names.

## Grant of Future License

We hereby irrevocably grant you an additional license to use the Software under
the Apache License, Version 2.0 that is effective on the second anniversary of
the date we make the Software available. On or after that date, you may use the
Software under the Apache License, Version 2.0, in which case the following
will apply:

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.

You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: TheBushidoCollective
Original project: https://github.com/TheBushidoCollective/han/blob/19caa51d5fd144ef6b2764f2332f4c856aa5d1af/plugins/tools/bun/skills/bun-bundler/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, Frontend Developer, Full-Stack Developer
Specialties: Backend
Tools: Bun
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 98e4af26667cae55a7910c0fabbff234d9f9ab65a5d2d1af67d1a2e31cb375f7
