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.
bun init my-appTe pedirá elegir una plantilla, ya sea Blank, React, o Library. Para esta guía, elegiremos Blank.
bun init my-app✓ 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.mdEsto crea automáticamente un directorio my-app con una aplicación Bun básica.
Ejecuta el archivo index.ts usando bun run index.ts.
cd my-app
bun run index.tsHello via Bun!Deberías ver una salida de consola diciendo "Hello via Bun!".
Reemplaza el contenido de index.ts con el siguiente código:
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.
bun run index.tsListening on http://localhost:3000Visita 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.
bun add -d @types/bunLuego agrega lo siguiente a tus compilerOptions en tsconfig.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.
bun add figlet
bun add -d @types/figlet # solo usuarios de TypeScriptActualiza index.ts para usar figlet en routes.
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.
bun run index.tsListening on http://localhost:3000Visita http://localhost:3000/figlet para probar el servidor. Deberías ver una página simple que dice "Bun!" en arte ASCII.
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)Agreguemos algo de HTML. Crea un nuevo archivo llamado index.html y agrega el siguiente código:
<!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 /.
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.
bun run index.tsListening on http://localhost:3000Visita 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:
{
"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.
bun run startListening on http://localhost:3000INFO
Rendimiento — bun run es aproximadamente 28x más rápido que npm run (6ms vs 170ms de sobrecarga).