Bun : runtime, bundler et tests

VérifiéSûr

Guide pratique pour Bun : installation, gestion de paquets avec bun.lock, serveur HTTP via Bun.serve, tests et migration depuis Node.js, avec les pièges à éviter.

Spar Skills Guide Bot
DeveloppementIntermédiaire
16/11/2026
Claude CodeCursorWindsurfCopilotCodex
#bun#javascript-runtime#package-manager#typescript#http-server

Recommandé pour

Synthèse automatique

Guide l'agent dans l'installation et l'usage de Bun comme runtime JavaScript/TypeScript, gestionnaire de paquets, bundler et lanceur de tests.

Points forts

  • Commandes précises et vérifiées pour installer Bun, initialiser un projet, gérer les dépendances et verrouiller les versions en CI.
  • Exemple serveur complet et cohérent combinant Bun.serve(), le routage par paramètres, bun:sqlite et Bun.password.
  • Réflexes de sécurité explicites : écoute sur la loopback par défaut, lecture du script d'installation avant exécution, gestion de trustedDependencies et de install.minimumReleaseAge.
  • Signale les écarts de compatibilité Node.js et la migration du lockfile binaire vers bun.lock textuel.

Limites

  • Le bundler et le lanceur de tests sont annoncés dans la description mais aucun exemple ni commande bun build / bun test n'est fourni.
  • Les différences de compatibilité avec Node.js sont mentionnées sans être énumérées, ce qui laisse l'agent sans critère de décision.
  • Le texte source s'interrompt au milieu d'une phrase sur Bun.password.verify, donc la partie authentification est incomplète.
Quand l'utiliser

À utiliser pour démarrer ou migrer un projet JS/TS vers Bun, gérer ses dépendances avec bun install ou écrire une API HTTP avec Bun.serve.

Quand l'éviter

À éviter si le besoin porte sur le bundling ou les tests avec Bun, ou si la cible impose un environnement Node.js dont la compatibilité n'est pas vérifiée.

Analyse de sécurité

Sûr
Score qualité90/100

The skill is documentation for Bun with normal development commands (installing packages, running a local server, tests, bundling). It explicitly advises against piping the Bun install script directly into a shell and recommends binding development servers to loopback. The sample password is clearly illustrative, and there is no obfuscation, destructive command, credential exfiltration, or safety-disabling instruction.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Scaffold a Bun API server
Create a new Bun project with bun init, then write a server.ts using Bun.serve with a /health route and a /api/users/:id route backed by bun:sqlite, bound to 127.0.0.1 on port 3000.
Migrate a Node project to Bun
Switch this Node.js repo over to Bun: convert the binary bun.lockb to bun.lock, run bun install, and tell me which dependencies need entries in trustedDependencies because they rely on postinstall scripts.
Harden dependency installs in CI
Set up our CI install step with Bun using a frozen lockfile and bun audit, and configure install.minimumReleaseAge in bunfig.toml so brand-new package releases are held back.

name: bun description: >- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime. license: Apache-2.0 compatibility: "Bun 1.4 on macOS, Linux or Windows (x64, arm64)" metadata: author: terminal-skills repository: https://github.com/oven-sh/bun version: "1.1.0" category: development tags: "bun, javascript-runtime, package-manager, bundler, typescript"

Bun

Overview

Bun is a single binary that is a JavaScript/TypeScript runtime, a package manager, a bundler and a Jest-compatible test runner. It runs .ts and .tsx files directly, reads .env files, and ships built-ins such as Bun.serve(), bun:sqlite and Bun.password. It targets Node.js compatibility, so most npm packages work, but not every Node API behaves identically. Checked against Bun 1.4.4.

Instructions

Install and start a project

npm install -g bun            # or: brew install oven-sh/bun/bun   (macOS, Linux)
bun --version                 # 1.4.x
bun init -y                   # package.json, tsconfig.json, index.ts, bun.lock
bun run index.ts              # run TypeScript directly; add --hot to reload on change

Bun also publishes an install script at https://bun.com/install; if you use it, download it, read it, then run it, rather than piping it into a shell. A package manager is simpler. On Windows use scoop install bun or npm install -g bun.

Packages

bun install                   # reads package.json, writes bun.lock (text lockfile, readable diffs)
bun add zod                   # add a dependency; bun add -d typescript for dev
bun remove zod
bun install --frozen-lockfile # CI: fail if package.json and bun.lock disagree
bun audit                     # vulnerability check; bun outdated lists newer versions
bunx prisma generate          # run a package binary without installing it globally

Bun does not run postinstall and similar lifecycle scripts of dependencies, except for a built-in allow list of popular packages. If a package needs one (native builds), list it in "trustedDependencies" in package.json and reinstall. To hold back brand-new releases, set install.minimumReleaseAge (seconds) in bunfig.toml. A project still on the old binary bun.lockb migrates with bun install --save-text-lockfile --frozen-lockfile --lockfile-only, then delete bun.lockb.

HTTP server

Bun.serve() takes a routes map with :param segments and per-method handlers; fetch handles everything else.

// server.ts
import { Database } from "bun:sqlite";

const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE, hash TEXT)");

const server = Bun.serve({
  port: 3000,
  hostname: "127.0.0.1", // bind to loopback unless the service must be reachable from outside
  routes: {
    "/health": new Response("ok"),
    "/api/users/:id": (req) => {
      const user = db.query("SELECT id, email FROM users WHERE id = ?1").get(req.params.id);
      return user ? Response.json(user) : new Response("Not found", { status: 404 });
    },
    "/api/users": {
      POST: async (req) => {
        const { email, password } = await req.json();
        const hash = await Bun.password.hash(password); // argon2id by default
        db.query("INSERT INTO users (email, hash) VALUES (?1, ?2)").run(email, hash);
        return Response.json({ email }, { status: 201 });
      },
    },
  },
  fetch() {
    return new Response("Not found", { status: 404 });
  },
});
console.log(`listening on ${server.url}`);

WebSockets: call server.upgrade(req) inside fetch and add a websocket: { message(ws, msg) { ws.send(...) } } handler to the same Bun.serve() options. Bun.password.verify(password, hash) checks a hash.

Tests

bun test finds *.test.ts files and supports describe, it, expect, snapshots and --coverage.

// mailer.ts
export async function sendWelcome(email: string) { /* send the mail */ }

// signup.ts
import { sendWelcome } from "./mailer";
export async function signup(email: string) {
  await sendWelcome(email);
  return { email, welcomed: true };
}
// signup.test.ts
import { describe, expect, it, mock } from "bun:test";

mock.module("./mailer", () => ({ sendWelcome: mock(async () => {}) })); // before importing the code under test

describe("signup", () => {
  it("welcomes the new user", async () => {
    const { signup } = await import("./signup");
    expect(await signup("mara@acme-corp.net")).toEqual({ email: "mara@acme-corp.net", welcomed: true });
  });
});

Bundle and compile

// build.ts — run with: bun run build.ts
const result = await Bun.build({
  entrypoints: ["./src/index.tsx"],
  outdir: "./dist",
  target: "browser", // "bun" or "node" for server code
  splitting: true,
  minify: true,
});
if (!result.success) console.error(result.logs);

CLI equivalent: bun build ./src/index.tsx --outdir dist --minify. bun build ./server.ts --compile --outfile dist/api produces a single self-contained executable.

Files and environment

Bun.file("data.json").json() reads and await Bun.write("out.txt", text) writes. new Bun.Glob("src/**/*.ts").scan(".") lists files. .env, .env.local and .env.<NODE_ENV> load automatically into Bun.env and process.env, so dotenv is not needed.

Examples

Example 1: Build an API server with only built-ins

User prompt: "Create a small REST API with Bun: POST /api/users stores an email and a hashed password, GET /api/users/:id returns a user."

The agent runs bun init -y, writes server.ts with Bun.serve() routes, bun:sqlite for storage and Bun.password.hash() for passwords, and starts it with bun run server.ts. It checks the result with curl -X POST -H 'content-type: application/json' -d '{"email":"mara@acme-corp.net","password":"correct-horse-9271"}' http://127.0.0.1:3000/api/users, which returns {"email":"mara@acme-corp.net"} with status 201, and shows that an unknown path returns 404.

Example 2: Move an Express project from Node.js to Bun

User prompt: "Switch my Express project from Node.js to Bun and make CI faster."

The agent deletes package-lock.json, runs bun install to create bun.lock, changes the scripts to bun run src/index.ts and bun test, and removes dotenv and ts-node. It runs the existing Jest tests under bun test, fixes the few that rely on Jest-only APIs, then sets the CI install step to bun install --frozen-lockfile. If a dependency fails on a missing Node API, it keeps that service on Node and reports the package name.

Guidelines

  • Commit bun.lock; use bun install --frozen-lockfile in CI
  • Dependency lifecycle scripts are blocked by default; add only packages you trust to trustedDependencies
  • Bun.serve() listens on all interfaces unless hostname is set; bind to 127.0.0.1 behind a reverse proxy
  • Prefer Bun.password over adding bcrypt packages, and do not store plain passwords
  • bun:sqlite is for embedded, single-process storage; use a server database for multi-instance deployments
  • Node compatibility is high but incomplete: test native addons and unusual node: APIs before switching production
  • Do not benchmark-claim from marketing numbers; measure your own workload
  • Use bunx instead of npx, and bun run <script> instead of npm run <script>

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/bun-runtime-bundler-tests-mwirmdv8/download' --output '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md.part' && mv '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md.part' '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Environnement déclaré par l’auteur : Bun 1.4 on macOS, Linux or Windows (x64, arm64)

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.claude/skills/bun'

Cursor
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.cursor/skills/bun'

Codex
test -f '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && test -s '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/bun' && cp -R '.skill-downloads/bun-runtime-bundler-tests-mwirmdv8' '.agents/skills/bun'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/bun-runtime-bundler-tests-mwirmdv8'

openskills read 'bun-runtime-bundler-tests-mwirmdv8'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/bun-runtime-bundler-tests-mwirmdv8/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires