
Bun Build
- 46 installs
- 4 repo stars
- Updated January 26, 2026
- daleseo/bun-skills
Sets up production bundles with Bun's native bundler for browser, Node, library, or CLI targets, replacing webpack, esbuild, or rollup.
About
Configures Bun.build production bundling with target selection, tree shaking, code splitting, and custom plugins. Developers use it when building apps for production or migrating off webpack/esbuild/rollup.
- Build targets for browser, Node.js, library, and CLI
- Tree shaking, code splitting, and custom loader plugins
Bun Build by the numbers
- 46 all-time installs (skills.sh)
- Ranked #760 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/daleseo/bun-skills --skill bun-buildAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 46 |
|---|---|
| repo stars | ★ 4 |
| Last updated | January 26, 2026 |
| Repository | daleseo/bun-skills ↗ |
What it does
Sets up production bundles with Bun's native bundler for browser, Node, library, or CLI targets, replacing webpack, esbuild, or rollup.
Files
Bun Production Build Configuration
Set up production builds using Bun's native bundler - fast, optimized bundle creation without webpack or esbuild.
Quick Reference
For detailed patterns, see:
- Build Targets: targets.md - Browser, Node.js, library, CLI configurations
- Optimization: optimization.md - Tree shaking, code splitting, analysis
- Plugins: plugins.md - Custom loaders and transformations
Core Workflow
1. Check Prerequisites
# Verify Bun installation
bun --version
# Check project structure
ls -la package.json src/2. Determine Build Requirements
Ask the user about their build needs:
- Application Type: Frontend SPA, Node.js backend, CLI tool, or library
- Target Platform: Browser, Node.js, Bun runtime, or Cloudflare Workers
- Output Format: ESM (modern), CommonJS (legacy), or both
3. Create Basic Build Script
Create build.ts in project root:
#!/usr/bin/env bun
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser', // or 'node', 'bun'
format: 'esm', // or 'cjs', 'iife'
minify: true,
splitting: true,
sourcemap: 'external',
});
if (!result.success) {
console.error('Build failed');
for (const message of result.logs) {
console.error(message);
}
process.exit(1);
}
console.log('✅ Build successful');
console.log(`📦 ${result.outputs.length} files generated`);
// Show bundle sizes
for (const output of result.outputs) {
const size = (output.size / 1024).toFixed(2);
console.log(` ${output.path} - ${size} KB`);
}4. Configure for Target Platform
For Browser/Frontend:
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
target: 'browser',
format: 'esm',
minify: true,
splitting: true,
define: {
'process.env.NODE_ENV': '"production"',
},
loader: {
'.png': 'file',
'.svg': 'dataurl',
'.css': 'css',
},
});For Node.js Backend:
await Bun.build({
entrypoints: ['./src/server.ts'],
outdir: './dist',
target: 'node',
format: 'esm',
minify: true,
external: ['*'], // Don't bundle node_modules
});For libraries, CLI tools, and other targets, see targets.md.
5. Add Production Optimizations
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
// Maximum minification
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
// Code splitting for optimal caching
splitting: true,
// Content hashing for cache busting
naming: {
entry: '[dir]/[name].[hash].[ext]',
chunk: 'chunks/[name].[hash].[ext]',
asset: 'assets/[name].[hash].[ext]',
},
// Source maps for debugging
sourcemap: 'external',
});For advanced optimizations (tree shaking, bundle analysis, size limits), see optimization.md.
6. Environment-Specific Builds
Create build-env.ts:
#!/usr/bin/env bun
const env = process.env.NODE_ENV || 'development';
const configs = {
development: {
minify: false,
sourcemap: 'inline',
define: {
'process.env.NODE_ENV': '"development"',
'process.env.API_URL': '"http://localhost:3000"',
},
},
production: {
minify: true,
sourcemap: 'external',
define: {
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.example.com"',
},
},
};
const config = configs[env as keyof typeof configs];
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
format: 'esm',
splitting: true,
...config,
});
if (!result.success) {
console.error('❌ Build failed');
process.exit(1);
}
console.log(`✅ ${env} build successful`);Run with:
NODE_ENV=production bun run build-env.ts7. Update package.json
Add build scripts:
{
"scripts": {
"build": "bun run build.ts",
"build:dev": "NODE_ENV=development bun run build-env.ts",
"build:prod": "NODE_ENV=production bun run build-env.ts",
"build:watch": "bun run build.ts --watch",
"clean": "rm -rf dist"
}
}For libraries, also add:
{
"type": "module",
"main": "./dist/cjs/index.js",
"module": "./dist/esm/index.js",
"types": "./dist/esm/index.d.ts",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/esm/index.d.ts"
}
},
"files": ["dist"]
}8. Generate Type Declarations (Libraries)
For libraries, generate TypeScript declarations:
// build-lib-with-types.ts
import { $ } from 'bun';
// Build JavaScript
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'node',
format: 'esm',
minify: true,
});
// Generate type declarations
await $`bunx tsc --declaration --emitDeclarationOnly --outDir dist`;
console.log('✅ Built library with type declarations');Build Options Reference
Target
- `browser`: For web applications (includes browser globals)
- `node`: For Node.js applications (assumes Node.js APIs)
- `bun`: For Bun runtime (optimized for Bun-specific features)
Format
- `esm`: ES Modules (modern, tree-shakeable) - Recommended
- `cjs`: CommonJS (legacy Node.js)
- `iife`: Immediately Invoked Function Expression (browser scripts)
Minification
minify: true // Basic minification
minify: { // Granular control
whitespace: true,
identifiers: true,
syntax: true,
}Source Maps
- `external`: Separate .map files (production)
- `inline`: Inline in bundle (development)
- `none`: No source maps
Verification
After building:
# 1. Check output directory
ls -lh dist/
# 2. Verify bundle size
du -sh dist/*
# 3. Test bundle
bun run dist/index.js
# 4. Check for errors
echo $? # Should be 0Common Build Patterns
Watch mode for development:
import { watch } from 'fs';
async function build() {
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
minify: false,
});
}
await build();
watch('./src', { recursive: true }, async (event, filename) => {
if (filename?.endsWith('.ts')) {
console.log(`Rebuilding...`);
await build();
}
});Custom asset loaders:
loader: {
'.png': 'file', // Copy file, return path
'.svg': 'dataurl', // Inline as data URL
'.txt': 'text', // Inline as string
'.json': 'json', // Parse and inline
}For custom plugins and advanced transformations, see plugins.md.
Troubleshooting
Build fails:
if (!result.success) {
for (const log of result.logs) {
console.error(log);
}
}Bundle too large: See optimization.md for:
- Bundle analysis
- Code splitting
- Tree shaking
- Size limits
Module not found: Check external configuration:
external: ['*'] // Exclude all node_modules
external: ['react'] // Exclude specific packages
external: [] // Bundle everythingCompletion Checklist
- ✅ Build script created
- ✅ Target platform configured
- ✅ Minification enabled
- ✅ Source maps configured
- ✅ Environment-specific builds set up
- ✅ Package.json scripts added
- ✅ Build tested successfully
- ✅ Bundle size verified
Next Steps
After basic build setup:
1. Optimization: Add bundle analysis and size limits 2. CI/CD: Automate builds in your pipeline 3. Type Checking: Add pre-build type checking 4. Testing: Run tests before building 5. Deployment: Integrate with bun-deploy for containerization
For detailed implementations, see the reference files linked above.
Build Optimization Strategies
Code Splitting
Enable code splitting for optimal caching:
await Bun.build({
entrypoints: [
'./src/index.ts',
'./src/admin.ts', // Separate entry for admin panel
],
outdir: './dist',
target: 'browser',
splitting: true, // Enable code splitting
naming: {
entry: '[dir]/[name].[ext]',
chunk: 'chunks/[name]-[hash].[ext]',
asset: 'assets/[name]-[hash].[ext]',
},
});Tree Shaking
Tree shaking is automatic, but you can help:
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
minify: true,
// Remove debug code
define: {
'process.env.DEBUG': 'false',
'__DEV__': 'false',
},
// Mark side-effect-free packages
external: [],
});Use named exports for better tree shaking:
// ❌ Harder to tree shake
export default { foo, bar, baz };
// ✅ Tree shakeable
export { foo, bar, baz };Minification
Basic Minification
await Bun.build({
minify: true, // Simple boolean
});Granular Minification
await Bun.build({
minify: {
whitespace: true, // Remove whitespace
identifiers: true, // Shorten variable names
syntax: true, // Simplify syntax
},
});Source Maps
await Bun.build({
sourcemap: 'external', // Separate .map files
// or
sourcemap: 'inline', // Inline in bundle
// or
sourcemap: 'none', // No source maps
});Asset Loaders
await Bun.build({
loader: {
'.png': 'file', // Copy file, return path
'.jpg': 'file',
'.svg': 'dataurl', // Inline as data URL
'.css': 'css', // Process as CSS
'.txt': 'text', // Inline as string
'.json': 'json', // Inline as JSON
},
// Public path for assets
publicPath: '/static/',
});Bundle Analysis
Create build-analyze.ts:
#!/usr/bin/env bun
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
minify: true,
splitting: true,
sourcemap: 'external',
});
// Analyze bundle sizes
interface BundleAnalysis {
total: number;
byType: Record<string, { size: number; count: number }>;
largest: Array<{ path: string; size: number }>;
}
const analysis: BundleAnalysis = {
total: 0,
byType: {},
largest: [],
};
for (const output of result.outputs) {
const size = output.size;
const ext = output.path.split('.').pop() || 'unknown';
analysis.total += size;
if (!analysis.byType[ext]) {
analysis.byType[ext] = { size: 0, count: 0 };
}
analysis.byType[ext].size += size;
analysis.byType[ext].count++;
analysis.largest.push({
path: output.path,
size: size,
});
}
// Sort by size
analysis.largest.sort((a, b) => b.size - a.size);
analysis.largest = analysis.largest.slice(0, 10);
// Report
console.log('\n📊 Bundle Analysis\n');
console.log(`Total Size: ${(analysis.total / 1024).toFixed(2)} KB`);
console.log(`Files: ${result.outputs.length}\n`);
console.log('By Type:');
for (const [type, data] of Object.entries(analysis.byType)) {
const sizeKB = (data.size / 1024).toFixed(2);
console.log(` ${type}: ${sizeKB} KB (${data.count} files)`);
}
console.log('\nLargest Files:');
for (const file of analysis.largest) {
const sizeKB = (file.size / 1024).toFixed(2);
const name = file.path.split('/').pop();
console.log(` ${name}: ${sizeKB} KB`);
}
// Check size limits
const MAX_BUNDLE_SIZE = 500 * 1024; // 500 KB
if (analysis.total > MAX_BUNDLE_SIZE) {
console.warn('\n⚠️ Warning: Bundle exceeds 500 KB');
process.exit(1);
}Environment-Specific Builds
#!/usr/bin/env bun
const env = process.env.NODE_ENV || 'development';
const configs = {
development: {
minify: false,
sourcemap: 'inline',
define: {
'process.env.NODE_ENV': '"development"',
'process.env.API_URL': '"http://localhost:3000"',
},
},
staging: {
minify: true,
sourcemap: 'external',
define: {
'process.env.NODE_ENV': '"staging"',
'process.env.API_URL': '"https://staging-api.example.com"',
},
},
production: {
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
sourcemap: 'external',
define: {
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.example.com"',
},
},
};
const config = configs[env as keyof typeof configs];
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
format: 'esm',
splitting: true,
...config,
});
if (!result.success) {
console.error('❌ Build failed');
process.exit(1);
}
console.log(`✅ ${env} build successful`);Run with:
NODE_ENV=production bun run build-env.tsPerformance Tips
1. Use --hot for development: Faster than full rebuilds 2. Enable code splitting: Better caching 3. Externalize dependencies: Don't bundle node_modules for backend 4. Use proper loaders: 'dataurl' for small files, 'file' for large 5. Enable minification: Only in production
Watch Mode
// build-watch.ts
import { watch } from 'fs';
async function build() {
console.log('🔨 Building...');
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'browser',
minify: false,
sourcemap: 'inline',
});
if (result.success) {
console.log('✅ Build complete');
} else {
console.error('❌ Build failed');
}
}
// Initial build
await build();
// Watch for changes
watch('./src', { recursive: true }, async (event, filename) => {
if (filename?.endsWith('.ts') || filename?.endsWith('.tsx')) {
console.log(`\n📝 ${filename} changed`);
await build();
}
});
console.log('\n👀 Watching for changes...');Bundle Size Limits
Enforce size limits:
const MAX_SIZES = {
total: 500 * 1024, // 500 KB total
chunk: 200 * 1024, // 200 KB per chunk
};
for (const output of result.outputs) {
if (output.size > MAX_SIZES.chunk) {
console.error(`❌ Chunk too large: ${output.path}`);
process.exit(1);
}
}
const totalSize = result.outputs.reduce((sum, o) => sum + o.size, 0);
if (totalSize > MAX_SIZES.total) {
console.error(`❌ Total bundle too large: ${totalSize} bytes`);
process.exit(1);
}Build Plugins and Custom Loaders
Custom Plugin System
Bun supports custom plugins for transforming files during the build process.
Plugin Interface
import type { BunPlugin } from 'bun';
const myPlugin: BunPlugin = {
name: 'my-plugin',
setup(build) {
// Plugin implementation
},
};Example: Inline SVG Plugin
import type { BunPlugin } from 'bun';
const inlineSvgPlugin: BunPlugin = {
name: 'inline-svg',
setup(build) {
build.onLoad({ filter: /\.svg$/ }, async (args) => {
const text = await Bun.file(args.path).text();
// Only inline small SVGs
if (text.length < 10000) {
return {
contents: `export default ${JSON.stringify(text)}`,
loader: 'js',
};
}
return undefined; // Use default loader
});
},
};
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
plugins: [inlineSvgPlugin],
});Example: Banner/Footer Plugin
const bannerPlugin: BunPlugin = {
name: 'banner',
setup(build) {
build.onLoad({ filter: /.*/ }, async (args) => {
const contents = await Bun.file(args.path).text();
const banner = `/* Built with Bun v${Bun.version} */\n`;
return {
contents: banner + contents,
loader: 'js',
};
});
},
};Example: Environment Variables Plugin
const envPlugin: BunPlugin = {
name: 'env-plugin',
setup(build) {
build.onLoad({ filter: /\.ts$/ }, async (args) => {
let contents = await Bun.file(args.path).text();
// Replace process.env.VAR with actual values
contents = contents.replace(
/process\.env\.(\w+)/g,
(_, key) => JSON.stringify(process.env[key] || '')
);
return {
contents,
loader: 'ts',
};
});
},
};Example: CSS Modules Plugin
const cssModulesPlugin: BunPlugin = {
name: 'css-modules',
setup(build) {
build.onLoad({ filter: /\.module\.css$/ }, async (args) => {
const css = await Bun.file(args.path).text();
// Simple CSS modules implementation
const classNames: Record<string, string> = {};
const transformed = css.replace(
/\.([a-zA-Z0-9_-]+)/g,
(_, className) => {
const hashed = `${className}_${hash(args.path)}`;
classNames[className] = hashed;
return `.${hashed}`;
}
);
return {
contents: `
export default ${JSON.stringify(classNames)};
const style = document.createElement('style');
style.textContent = ${JSON.stringify(transformed)};
document.head.appendChild(style);
`,
loader: 'js',
};
});
},
};
function hash(str: string): string {
return Bun.hash(str).toString(36).slice(0, 6);
}Example: Image Optimization Plugin
const imageOptimizePlugin: BunPlugin = {
name: 'image-optimize',
setup(build) {
build.onLoad({ filter: /\.(png|jpg|jpeg)$/ }, async (args) => {
// Use sharp or other image library to optimize
const buffer = await Bun.file(args.path).arrayBuffer();
// Placeholder: In real implementation, optimize image
const optimized = buffer;
// Write optimized file
const outputPath = args.path.replace(/src/, 'dist');
await Bun.write(outputPath, optimized);
return {
contents: `export default ${JSON.stringify(outputPath)}`,
loader: 'js',
};
});
},
};Example: TypeScript Path Alias Plugin
const pathAliasPlugin: BunPlugin = {
name: 'path-alias',
setup(build) {
const aliases = {
'@/': './src/',
'@components/': './src/components/',
'@utils/': './src/utils/',
};
build.onResolve({ filter: /^@\// }, (args) => {
for (const [alias, path] of Object.entries(aliases)) {
if (args.path.startsWith(alias)) {
return {
path: args.path.replace(alias, path),
};
}
}
});
},
};Example: Markdown Plugin
const markdownPlugin: BunPlugin = {
name: 'markdown',
setup(build) {
build.onLoad({ filter: /\.md$/ }, async (args) => {
const markdown = await Bun.file(args.path).text();
// Use markdown parser (simplified)
const html = markdownToHtml(markdown);
return {
contents: `export default ${JSON.stringify(html)}`,
loader: 'js',
};
});
},
};
function markdownToHtml(md: string): string {
// Simplified - use marked or similar in production
return md.replace(/^# (.+)$/gm, '<h1>$1</h1>');
}Example: JSON Import with Validation
import { z } from 'zod';
const jsonSchemaPlugin: BunPlugin = {
name: 'json-schema',
setup(build) {
build.onLoad({ filter: /\.json$/ }, async (args) => {
const json = await Bun.file(args.path).json();
// Define schema for validation
const schema = z.object({
name: z.string(),
version: z.string(),
});
// Validate
try {
schema.parse(json);
} catch (error) {
throw new Error(`Invalid JSON in ${args.path}: ${error}`);
}
return {
contents: `export default ${JSON.stringify(json)}`,
loader: 'js',
};
});
},
};Using Multiple Plugins
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
plugins: [
inlineSvgPlugin,
cssModulesPlugin,
pathAliasPlugin,
markdownPlugin,
],
});Plugin Execution Order
Plugins execute in the order they're defined:
plugins: [
plugin1, // Runs first
plugin2, // Runs second
plugin3, // Runs third
]Error Handling in Plugins
const safePlugin: BunPlugin = {
name: 'safe-plugin',
setup(build) {
build.onLoad({ filter: /\.custom$/ }, async (args) => {
try {
const contents = await Bun.file(args.path).text();
return {
contents: transform(contents),
loader: 'js',
};
} catch (error) {
console.error(`Error processing ${args.path}:`, error);
throw error; // Re-throw to fail build
}
});
},
};Plugin Best Practices
1. Name your plugins: Always set a descriptive name 2. Handle errors gracefully: Catch and report errors clearly 3. Use specific filters: Don't match more files than necessary 4. Cache when possible: Avoid redundant work 5. Document dependencies: List any required packages
Testing Plugins
// test-plugin.ts
import { test, expect } from 'bun:test';
test('inline SVG plugin', async () => {
const result = await Bun.build({
entrypoints: ['./test/fixtures/app.ts'],
plugins: [inlineSvgPlugin],
});
expect(result.success).toBe(true);
// Additional assertions
});Build Targets and Configurations
Complete configurations for different build targets using Bun's native bundler.
Browser/Frontend Build
// build-browser.ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
target: 'browser',
format: 'esm',
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
splitting: true,
sourcemap: 'external',
external: [], // Bundle everything
define: {
'process.env.NODE_ENV': '"production"',
'process.env.API_URL': '"https://api.example.com"',
},
loader: {
'.png': 'file',
'.jpg': 'file',
'.svg': 'file',
'.css': 'css',
},
});Node.js Backend Build
// build-node.ts
await Bun.build({
entrypoints: ['./src/server.ts'],
outdir: './dist',
target: 'node',
format: 'esm',
minify: true,
sourcemap: 'inline',
external: ['*'], // Don't bundle node_modules
// Or be explicit:
// external: ['express', 'mongodb', 'redis'],
});Library Build (Dual Format)
// build-library.ts
// ESM build
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist/esm',
target: 'node',
format: 'esm',
minify: true,
sourcemap: 'external',
external: ['*'],
});
// CommonJS build
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist/cjs',
target: 'node',
format: 'cjs',
minify: true,
sourcemap: 'external',
external: ['*'],
});
console.log('✅ Built ESM and CJS formats');Update package.json:
{
"type": "module",
"main": "./dist/cjs/index.js",
"module": "./dist/esm/index.js",
"types": "./dist/esm/index.d.ts",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/esm/index.d.ts"
}
},
"files": ["dist"]
}CLI Tool Build
// build-cli.ts
await Bun.build({
entrypoints: ['./src/cli.ts'],
outdir: './dist',
target: 'bun',
format: 'esm',
minify: true,
// Bundle everything for single-file distribution
external: [],
});
// Make executable
import { chmod } from 'fs/promises';
await chmod('./dist/cli.js', 0o755);
console.log('✅ CLI built and made executable');Update package.json:
{
"bin": {
"your-cli-name": "./dist/cli.js"
}
}Cloudflare Workers
// build-worker.ts
await Bun.build({
entrypoints: ['./src/worker.ts'],
outdir: './dist',
target: 'browser',
format: 'esm',
minify: true,
external: [],
});Bun Runtime Target
// build-bun.ts
await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'bun',
format: 'esm',
minify: true,
// Can use Bun-specific features
});Target Comparison
| Target | Use Case | Node APIs | Browser APIs | Bun APIs |
|---|---|---|---|---|
browser | Frontend apps | ❌ | ✅ | ❌ |
node | Backend apps | ✅ | ❌ | ❌ |
bun | Bun-specific apps | ✅ | ❌ | ✅ |
Format Options
ESM (Recommended)
{
format: 'esm', // Modern, tree-shakeable
}Output:
export default function() {}
export { foo, bar };CommonJS
{
format: 'cjs', // Legacy Node.js
}Output:
module.exports = function() {}
exports.foo = foo;IIFE (Browser Scripts)
{
format: 'iife', // Self-contained browser script
}Output:
(function() {
// Your code
})();