Skip to content

Panoramica

Costruisci un server HTTP minimo con Bun.serve, eseguilo localmente, poi evolvilo installando un pacchetto.

::: Prerequisiti: Bun installato e disponibile nel tuo PATH. Vedi installazione per la configurazione. :::


Inizializza un nuovo progetto con bun init.

bash
bun init my-app

Ti chiederà di scegliere un template, tra Blank, React, o Library. Per questa guida, sceglieremo Blank.

bash
bun init my-app
bash
 Seleziona un template di progetto: Blank

- .gitignore
- CLAUDE.md
- .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
- index.ts
- tsconfig.json (per il completamento automatico dell'editor)
- README.md

Questo crea automaticamente una directory my-app con una app Bun di base.

Esegui il file index.ts usando bun run index.ts.

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

Dovresti vedere un output della console che dice "Hello via Bun!".

Sostituisci i contenuti di index.ts con il seguente codice:

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

console.log(`In ascolto su ${server.url}`);

Esegui di nuovo il file index.ts usando bun run index.ts.

bash
bun run index.ts
bash
In ascolto su http://localhost:3000

Visita http://localhost:3000 per testare il server. Dovresti vedere una pagina semplice che dice "Bun!".

Vedi errori TypeScript su Bun?

Se hai usato bun init, Bun avrà installato automaticamente le dichiarazioni TypeScript di Bun e configurato il tuo tsconfig.json. Se stai provando Bun in un progetto esistente, potresti vedere un errore di tipo sul globale Bun.

Per risolvere, prima installa @types/bun come dipendenza di sviluppo.

bash
bun add -d @types/bun

Poi aggiungi quanto segue alle tue compilerOptions in tsconfig.json:

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

Installa il pacchetto figlet e le sue dichiarazioni di tipo. Figlet è un'utilità per convertire stringhe in ASCII art.

bash
bun add figlet
bun add -d @types/figlet # Solo per utenti TypeScript

Aggiorna index.ts per usare figlet in 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);
    } 
  }
});

Esegui di nuovo il file index.ts usando bun run index.ts.

bash
bun run index.ts
bash
In ascolto su http://localhost:3000

Visita http://localhost:3000/figlet per testare il server. Dovresti vedere una pagina semplice che dice "Bun!" in ASCII art.

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

Aggiungiamo un po' di HTML. Crea un nuovo file chiamato index.html e aggiungi il seguente codice:

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>

Poi, importa questo file in index.ts e servilo dalla route root /.

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(`In ascolto su ${server.url}`);

Esegui di nuovo il file index.ts usando bun run index.ts.

bash
bun run index.ts
txt
In ascolto su http://localhost:3000

Visita http://localhost:3000 per testare il server. Dovresti vedere la pagina HTML statica.

🎉 Congratulazioni! Hai costruito un semplice server HTTP con Bun e installato un pacchetto.


Eseguire uno script

Bun può anche eseguire "scripts" dal tuo package.json. Aggiungi il seguente script:

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

Poi eseguilo con bun run start.

bash
bun run start
bash
In ascolto su http://localhost:3000

INFO

Prestazionibun run è circa 28 volte più veloce di npm run (6ms contro 170ms di overhead).

Bun a cura di www.bunjs.com.cn