bun-build
Create optimized production bundles with Bun's native bundler. Use when building applications for production, optimizing bundle sizes, setting up multi-environment builds, or replacing webpack/esbuild/rollup.
What this skill does
# 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](references/targets.md) - Browser, Node.js, library, CLI configurations
- **Optimization**: [optimization.md](references/optimization.md) - Tree shaking, code splitting, analysis
- **Plugins**: [plugins.md](references/plugins.md) - Custom loaders and transformations
## Core Workflow
### 1. Check Prerequisites
```bash
# 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:
```typescript
#!/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:**
```typescript
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:**
```typescript
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](references/targets.md).
### 5. Add Production Optimizations
```typescript
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](references/optimization.md).
### 6. Environment-Specific Builds
Create `build-env.ts`:
```typescript
#!/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:
```bash
NODE_ENV=production bun run build-env.ts
```
### 7. Update package.json
Add build scripts:
```json
{
"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:
```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"]
}
```
### 8. Generate Type Declarations (Libraries)
For libraries, generate TypeScript declarations:
```typescript
// 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
```typescript
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:
```bash
# 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 0
```
## Common Build Patterns
**Watch mode for development:**
```typescript
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:**
```typescript
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](references/plugins.md).
## Troubleshooting
**Build fails:**
```typescript
if (!result.success) {
for (const log of result.logs) {
console.error(log);
}
}
```
**Bundle too large:**
See [optimization.md](references/optimization.md) for:
- Bundle analysis
- Code splitting
- Tree shaking
- Size limits
**Module not found:**
Check `external` configuration:
```typescript
external: ['*'] // Exclude all node_modules
external: ['react'] // Exclude specific packages
external: [] // Bundle everything
```
## Completion 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 liRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.