Bun v1.x Migración Node → Bun Web · Desarrollo CULTIVA IA — Arsenal

Bun Runtime & Toolchain

Guía de migración completa: runtime, paquetes, tests y build en un solo comando

Cliente: LeadFlow SaaS  ·  Stack: Next.js + TypeScript · Vercel
Comparativa de velocidad — CI de LeadFlow (85 deps)
npm install
92 s
bun install
18 s
webpack build
47 s
bun build
8 s

Equivalencias de comandos

Node / npm / npx Bun equivalente Descripción
npm install bun install Instala dependencias; genera bun.lock
npm install express bun add express Añade dependencia de producción
npm install -D vitest bun add -d vitest Añade devDependency
node src/index.ts bun src/index.ts Ejecuta TS directamente, sin compilar
npm run dev bun run dev Ejecuta script de package.json
npx prisma generate bun x prisma generate Ejecuta binario sin instalar globalmente
jest bun test Test runner integrado, API compatible con Jest
webpack --mode=production bun build ./src --outdir=dist Bundler nativo de Bun
🧪

Tests con bun:test — LeadFlow Lead Scorer

src/leads/__tests__/scorer.test.ts TypeScript
import { expect, test, describe, beforeEach } from "bun:test";
import { scoreLead } from "../scorer";

describe("LeadFlow Scorer", () => {
  test("puntúa lead caliente correctamente", () => {
    const lead = {
      company_size: 50,
      visited_pricing: true,
      email_opens: 5,
      industry: "marketing"
    };
    expect(scoreLead(lead)).toBeGreaterThan(80);
  });

  test("lead frío score bajo", () => {
    const lead = { company_size: 2, visited_pricing: false, email_opens: 0 };
    expect(scoreLead(lead)).toBeLessThan(30);
  });
});
terminal BASH
# Ejecutar tests
bun test

# Watch mode durante desarrollo
bun test --watch

# Solo un archivo concreto
bun test src/leads/__tests__/scorer.test.ts
🔧

API nativa de Bun — Webhook receiver

src/webhooks/server.ts TypeScript
// Bun.file — leer config JSON sin fs nativa
const configFile = Bun.file("config/leadflow.json");
const config = await configFile.json<LeadFlowConfig>();

// Bun.serve — HTTP server nativo de alta performance
Bun.serve({
  port: config.webhook_port ?? 3001,
  async fetch(req: Request) {
    const url = new URL(req.url);

    if (url.pathname === "/webhook/lead" && req.method === "POST") {
      const body = await req.json();
      // Procesa el lead entrante
      await processInboundLead(body);
      return new Response(JSON.stringify({ ok: true }), {
        headers: { "Content-Type": "application/json" }
      });
    }

    return new Response("Not found", { status: 404 });
  }
});

console.log(`LeadFlow webhook server en :${config.webhook_port}`);

Configuración Vercel con Bun

vercel.json
{
  "installCommand": "bun install --frozen-lockfile",
  "buildCommand": "bun run build",
  "framework": "nextjs"
}
GitHub Actions CI
- uses: oven-sh/setup-bun@v1
  with:
    bun-version: latest

- run: bun install --frozen-lockfile
- run: bun test
- run: bun run build

Nota sobre lockfile

Usa --frozen-lockfile en CI para installs reproducibles. Bun ≥ 1.1 genera bun.lock (texto, versionable en git). Versiones anteriores generaban bun.lockb (binario). Hacer commit del lockfile es obligatorio para deploys deterministas.

🚀

Migración paso a paso — LeadFlow

1

Instalar Bun globalmente

curl -fsSL https://bun.sh/install | bash · Verificar: bun --version

2

Reemplazar node_modules y lockfile

Borrar node_modules/ y package-lock.json. Ejecutar bun install para generar bun.lock.

3

Verificar scripts de package.json

Sustituir npm run X por bun run X en docs y CI. Comprobar que bun run dev arranca sin errores.

4

Migrar tests de Jest a bun:test

Cambiar imports de "jest" a "bun:test". La API es compatible (describe/test/expect). Ejecutar bun test.

5

Actualizar Vercel y GitHub Actions

Añadir vercel.json con installCommand: bun install --frozen-lockfile. Usar oven-sh/setup-bun@v1 en CI.

Buenas prácticas

🔒
Lockfile en git siempre. Hacer commit de bun.lock garantiza installs idénticos en CI y producción. Nunca ignorarlo en .gitignore.
TypeScript nativo. Bun ejecuta .ts directamente. No necesitas ts-node ni compilar previamente para scripts y workers.
🧪
bun:test sobre Jest. Usa siempre import from "bun:test" en proyectos nuevos. Más rápido, sin config extra, API idéntica a Jest.
🌐
Bun.serve para webhooks internos. Para microservicios ligeros (webhooks, health checks, scripts HTTP) usa Bun.serve() sin Express ni Fastify.
🔄
Actualiza frecuentemente. Bun evoluciona rápido. Revisa el changelog en cada release mayor para aprovechar mejoras de compatibilidad con el ecosistema npm.