Loading...
Loading...
Comprehensive Bun runtime expertise covering all major features. Use when working with Bun projects, migrating from Node.js, or leveraging Bun-specific APIs. Activates for: Bun.serve, Bun.file, bun:test, bun:sqlite, bun install, bun build, bunfig.toml, TypeScript in Bun, package manager operations, bundler configuration, and Node.js compatibility questions.
npx skill4agent add lammesen/skills bun-expertBun.serve(options)Bun.fetch(url)Bun.connect()Bun.listen()Bun.dnsBun.file(path)Bun.write(path, data)Bun.stdinBun.stdoutBun.stderrBun.spawn(cmd)Bun.spawnSync(cmd)Bun.$\lscdrmcatechopwdmkdirtouchwhichmvbun:sqliteBun.sqlBun.S3ClientBun.s3Bun.redisBun.password.hash()Bun.password.verify()Bun.hash(data)Bun.GlobBun.semverBun.sleep(ms)Bun.sleepSync(ms)Bun.deepEquals(a, b)Bun.escapeHTML()Bun.YAML.parse()Bun.YAML.stringify()HTMLRewriterbun:ffiWorkerBroadcastChannelBun.TranspilerBun.build()bun install # Install all dependencies
bun install --frozen-lockfile # CI/CD lockfile validation
bun add <pkg> # Add dependency
bun add -d <pkg> # Add devDependency
bun remove <pkg> # Remove dependency
bun update # Update outdated packages
bun ci # CI-optimized install (--frozen-lockfile)
bunx <pkg> # Execute package without installing (100x faster than npx){
"workspaces": ["packages/*", "apps/*"],
"dependencies": {
"shared-pkg": "workspace:*"
}
}bun pm trust <pkg> # Allow lifecycle scripts
bun pm untrusted # View blocked scripts
bun why <pkg> # Explain why package installed
bun outdated # Show outdated packages
bun audit # Security vulnerability check
bun patch <pkg> # Prepare package for patching
bun link # Link local packagesbun.lockpackage-lock.jsonyarn.lockpnpm-lock.yamlimport { describe, test, expect, beforeAll, afterEach, mock, spyOn } from "bun:test";
describe("feature", () => {
beforeAll(() => { /* setup */ });
afterEach(() => { mock.restore(); });
test("basic assertion", () => {
expect(2 + 2).toBe(4);
});
test("async operation", async () => {
const result = await fetchData();
expect(result).toMatchObject({ status: "ok" });
});
test.each([[1, 2, 3], [2, 3, 5]])("adds %i + %i = %i", (a, b, expected) => {
expect(a + b).toBe(expected);
});
});test.skip()test.only()--onlytest.todo()test.if(condition)test.skipIf(condition)test.failing()test.concurrenttest.retry(n).toBe().toEqual().toStrictEqual().toContain().toHaveLength().toMatch().toHaveProperty().toMatchObject().toThrow().rejects.toThrow().toMatchSnapshot().toMatchInlineSnapshot().toHaveBeenCalled().toHaveBeenCalledWith()import { mock, spyOn } from "bun:test";
const mockFn = mock(() => 42);
mockFn.mockImplementation(() => 100);
mockFn.mockReturnValue(200);
const spy = spyOn(object, "method");
spy.mockResolvedValue({ data: "test" });
// Module mocking
mock.module("./api", () => ({
fetchUser: mock(() => ({ id: 1, name: "Test" }))
}));bun test # Run all tests
bun test --watch # Watch mode
bun test --coverage # Enable coverage
bun test -t "pattern" # Filter by test name
bun test --timeout=5000 # Set timeout
bun test --bail # Stop on first failure
bun test --update-snapshots # Update snapshotsconst result = await Bun.build({
entrypoints: ["./src/index.tsx"],
outdir: "./dist",
target: "browser", // "browser" | "bun" | "node"
format: "esm", // "esm" | "cjs" | "iife"
minify: true,
sourcemap: "external",
splitting: true, // Code splitting
external: ["react", "react-dom"],
define: {
"process.env.NODE_ENV": '"production"'
},
loader: {
".png": "dataurl",
".svg": "text"
},
plugins: [myPlugin],
naming: {
entry: "[dir]/[name].[ext]",
chunk: "[name]-[hash].[ext]"
}
});
if (!result.success) {
console.error(result.logs);
}bun build ./src/index.tsx --outdir ./dist --minify --sourcemap=external
bun build ./src/index.ts --compile --outfile myapp # Single executableconst myPlugin: BunPlugin = {
name: "yaml-loader",
setup(build) {
build.onLoad({ filter: /\.yaml$/ }, async (args) => {
const text = await Bun.file(args.path).text();
return {
contents: `export default ${JSON.stringify(YAML.parse(text))}`,
loader: "js"
};
});
}
};bun run index.ts # Just works
bun run index.tsx # JSX supported{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"types": ["bun-types"]
}
}bunx tsc --noEmit# Runtime
preload = ["./setup.ts"]
smol = true # Reduced memory mode
# JSX
[jsx]
runtime = "automatic"
importSource = "react"
# Package installation
[install]
optional = false
lockfile.save = true
[install.scopes]
"@myorg" = { url = "https://npm.myorg.com", token = "$NPM_TOKEN" }
# Test runner
[test]
preload = ["./test-setup.ts"]
coverage = true
coverageThreshold = { lines = 0.8, functions = 0.8 }--watch--hot--smol--inspect--inspect-brk--preload-r--install=auto|fallback|force--define-d--drop=console--loader--env-file--cwd--bun-bcurl -fsSL https://bun.sh/install | bash# Delete node_modules and lockfile
rm -rf node_modules package-lock.json yarn.lock pnpm-lock.yaml
bun install{
"scripts": {
"dev": "bun run --watch src/index.ts",
"test": "bun test",
"build": "bun build src/index.ts --outdir dist"
}
}bun add -d @types/bun
# Or in tsconfig.json: "types": ["bun-types"]node:assertnode:buffernode:eventsnode:pathnode:urlnode:fsnode:httpnode:httpsnode:streamnode:zlibnode:cryptonode:netnode:dnsnode:osnode:child_processproc.gidproc.uidnode:clusternode:http2pushStreamnode:worker_threadsstdinstdoutstderrnode:async_hooksnode:inspectornode:replnode:trace_eventsbcryptjsbcryptbun pm trust <package>trustedDependenciesModule._nodeModulePathsgraceful-fs"main"{
"main": "src/index.ts" // Not "build/index.js"
}bun installbun runbun test// Use Bun's native APIs for I/O
const file = Bun.file("large.txt"); // Zero-copy
const content = await file.text();
await Bun.write("output.txt", processedData);
// Use Promise.all for concurrent operations
const [users, posts] = await Promise.all([
db.query("SELECT * FROM users"),
db.query("SELECT * FROM posts")
]);
// Use Bun.serve() static routes
Bun.serve({
static: {
"/": homepage,
"/about": aboutPage
},
fetch(req) { /* dynamic routes */ }
});
// Use bun:sqlite for local data
import { Database } from "bun:sqlite";
const db = new Database(":memory:");
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");// HTTP server error handling
Bun.serve({
fetch(req) {
try {
return handleRequest(req);
} catch (error) {
console.error(error);
return new Response("Internal Error", { status: 500 });
}
},
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
}
});
// Process-level error handling
process.on("uncaughtException", (error) => {
console.error("Uncaught:", error);
process.exit(1);
});trustedDependencies.env.localbun audit--productionmy-bun-project/
├── src/
│ ├── index.ts # Entry point
│ ├── server.ts # HTTP server
│ └── lib/ # Utilities
├── test/
│ └── *.test.ts # Test files
├── bunfig.toml # Bun configuration
├── tsconfig.json # TypeScript config
├── package.json
└── .env.local # Local secrets (gitignored)bun --inspect server.ts # Start debugger
bun --inspect-brk server.ts # Break at first line
bun --inspect-wait server.ts # Wait for connectionhttps://debug.bun.shBUN_CONFIG_VERBOSE_FETCH=curl bun run server.tsBun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("Hello Bun!");
},
websocket: {
open(ws) { console.log("Connected"); },
message(ws, message) { ws.send(`Echo: ${message}`); },
close(ws) { console.log("Disconnected"); }
}
});Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
const file = Bun.file(`./public${path}`);
if (await file.exists()) {
return new Response(file);
}
return new Response("Not Found", { status: 404 });
}
});import { Database } from "bun:sqlite";
const db = new Database("app.db");
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)`);
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
const getAll = db.prepare("SELECT * FROM users");
insert.run("Alice", "alice@example.com");
const users = getAll.all();.ts.tsx.js.jsxbunfig.tomlbun.lockbun:testbun:sqlitebun:ffi