Skip to content

Visión General

Construye un servidor HTTP mínimo con Bun.serve, ejecútalo localmente, y evolucionalo instalando un paquete.

::: Requisitos previos: Bun instalado y disponible en tu PATH. Consulta instalación para configuración. :::


Inicializa un nuevo proyecto con bun init.

bash
bun init my-app

Te pedirá elegir una plantilla, ya sea Blank, React, o Library. Para esta guía, elegiremos Blank.

bash
bun init my-app
bash
 Selecciona una plantilla de proyecto: Blank

- .gitignore
- CLAUDE.md
- .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
- index.ts
- tsconfig.json (para autocompletado del editor)
- README.md

Esto crea automáticamente un directorio my-app con una aplicación Bun básica.

Ejecuta el archivo index.ts usando bun run index.ts.

bash
cd my-app
bun run index.ts
bash
Hello via Bun!

Deberías ver una salida de consola diciendo "Hello via Bun!".

Reemplaza el contenido de index.ts con el siguiente código:

ts
const server = Bun.serve({
  port: 3000,
  routes: {
    "/": () => new Response('Bun!'),
  }
});

console.log(`Listening on ${server.url}`);

Ejecuta el archivo index.ts nuevamente usando bun run index.ts.

bash
bun run index.ts
bash
Listening on http://localhost:3000

Visita http://localhost:3000 para probar el servidor. Deberías ver una página simple que dice "Bun!".

¿Ves errores de TypeScript en Bun?

Si usaste bun init, Bun habrá instalado automáticamente las declaraciones de tipos de Bun y configurado tu tsconfig.json. Si estás probando Bun en un proyecto existente, puedes ver un error de tipo en el global Bun.

Para solucionarlo, primero instala @types/bun como una dependencia de desarrollo.

bash
bun add -d @types/bun

Luego agrega lo siguiente a tus compilerOptions en tsconfig.json:

json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleDetection": "force",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true
  }
}

Instala el paquete figlet y sus declaraciones de tipos. Figlet es una utilidad para convertir cadenas en arte ASCII.

bash
bun add figlet
bun add -d @types/figlet # solo usuarios de TypeScript

Actualiza index.ts para usar figlet en routes.

ts
import figlet from 'figlet';

const server = Bun.serve({
  port: 3000,
  routes: {
    "/": () => new Response('Bun!'),
    "/figlet": () => {
      const body = figlet.textSync('Bun!');
      return new Response(body);
    } 
  }
});

Ejecuta el archivo index.ts nuevamente usando bun run index.ts.

bash
bun run index.ts
bash
Listening on http://localhost:3000

Visita http://localhost:3000/figlet para probar el servidor. Deberías ver una página simple que dice "Bun!" en arte ASCII.

bash
____              _
| __ ) _   _ _ __ | |
|  _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)

Agreguemos algo de HTML. Crea un nuevo archivo llamado index.html y agrega el siguiente código:

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bun</title>
  </head>
  <body>
    <h1>Bun!</h1>
  </body>
</html>

Luego, importa este archivo en index.ts y sírvelo desde la ruta raíz /.

ts
import figlet from 'figlet';
import index from './index.html'; 

const server = Bun.serve({
  port: 3000,
  routes: {
    "/": index, 
    "/figlet": () => {
      const body = figlet.textSync('Bun!');
      return new Response(body);
    }
  }
});

console.log(`Listening on ${server.url}`);

Ejecuta el archivo index.ts nuevamente usando bun run index.ts.

bash
bun run index.ts
txt
Listening on http://localhost:3000

Visita http://localhost:3000 para probar el servidor. Deberías ver la página HTML estática.

¡Felicidades! Has construido un servidor HTTP simple con Bun e instalado un paquete.


Ejecutar un script

Bun también puede ejecutar "scripts" desde tu package.json. Agrega el siguiente script:

json
{
  "name": "quickstart",
  "module": "index.ts",
  "type": "module",
  "private": true,
  "scripts": { 
    "start": "bun run index.ts"
  }, 
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5"
  }
}

Luego ejecútalo con bun run start.

bash
bun run start
bash
Listening on http://localhost:3000

INFO

Rendimientobun run es aproximadamente 28x más rápido que npm run (6ms vs 170ms de sobrecarga).

Bun por www.bunjs.com.cn editar