Skip to content

Il bundler di Bun ha supporto di prima classe per HTML. Costruisci siti statici, landing page e applicazioni web con zero configurazione. Basta puntare Bun al tuo file HTML e gestisce tutto il resto.

html
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="./styles.css" />
    <script src="./app.ts" type="module"></script>
  </head>
  <body>
    <img src="./logo.png" />
  </body>
</html>

Per iniziare, passa file HTML a bun.

bash
bun ./index.html
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Premi h + Enter per mostrare scorciatoie

Il server di sviluppo di Bun fornisce funzionalità potenti con zero configurazione:

  • Bundling Automatico - Bundla e serve il tuo HTML, JavaScript e CSS
  • Supporto Multi-Entry - Gestisce multiple entry point HTML e entry point glob
  • JavaScript Moderno - Supporto TypeScript & JSX out of the box
  • Configurazione Smart - Legge tsconfig.json per paths, opzioni JSX, decorators sperimentali, e altro
  • Plugin - Plugin per TailwindCSS e altro
  • ESM & CommonJS - Usa ESM e CommonJS nei tuoi file JavaScript, TypeScript e JSX
  • Bundling & Minificazione CSS - Bundla CSS da tag <link> e statement @import
  • Gestione Asset - Copia & hashing automatico di immagini e asset; Riscrive percorsi asset in JavaScript, CSS e HTML

Single Page Apps (SPA)

Quando passi un singolo file .html a Bun, Bun lo userà come route fallback per tutti i percorsi. Questo lo rende perfetto per single page app che usano routing client-side:

bash
bun index.html
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Premi h + Enter per mostrare scorciatoie

La tua React o altra SPA funzionerà out of the box — nessuna configurazione necessaria. Tutte le route come /about, /users/123, etc. serviranno lo stesso file HTML, lasciando il tuo router client-side gestire la navigazione.

html
<!doctype html>
<html>
  <head>
    <title>My SPA</title>
    <script src="./app.tsx" type="module"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Multi-page apps (MPA)

Alcuni progetti hanno diverse route separate o file HTML come entry point. Per supportare multiple entry point, passali tutti a bun:

bash
bun ./index.html ./about.html
txt
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about.html
Premi h + Enter per mostrare scorciatoie

Questo servirà:

  • index.html su /
  • about.html su /about

Pattern Glob

Per specificare multiple file, puoi usare pattern glob che terminano in .html:

bash
bun ./**/*.html
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about.html
Premi h + Enter per mostrare scorciatoie

Normalizzazione Percorsi

Il percorso base è scelto dal prefisso comune più lungo tra tutti i file.

bash
bun ./index.html ./about/index.html ./about/foo/index.html
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Routes:
  / ./index.html
  /about ./about/index.html
  /about/foo ./about/foo/index.html
Premi h + Enter per mostrare scorciatoie

JavaScript, TypeScript e JSX

Il transpiler di Bun implementa nativamente supporto JavaScript, TypeScript e JSX. Scopri di più sui loader in Bun.

NOTE

Il transpiler di Bun è anche usato a runtime.

ES Modules & CommonJS

Puoi usare ESM e CJS nei tuoi file JavaScript, TypeScript e JSX. Bun gestirà la transpilazione e il bundling automaticamente.

Non c'è pre-build o step di ottimizzazione separato. È tutto fatto allo stesso tempo.

Scopri di più sulla risoluzione moduli in Bun.

CSS

Il parser CSS di Bun è anche implementato nativamente (circa 58.000 righe di Zig).

È anche un bundler CSS. Puoi usare @import nei tuoi file CSS per importare altri file CSS.

Per esempio:

css
@import "./abc.css";

.container {
  background-color: blue;
}
css
body {
  background-color: red;
}

Questo output:

css
body {
  background-color: red;
}

.container {
  background-color: blue;
}

Referenziare asset locali in CSS

Puoi referenziare asset locali nei tuoi file CSS.

css
body {
  background-image: url("./logo.png");
}

Questo copierà ./logo.png nella directory di output e riscriverà il percorso nel file CSS per includere un hash del contenuto.

css
body {
  background-image: url("./logo-[ABC123].png");
}

Importare CSS in JavaScript

Per associare un file CSS con un file JavaScript, puoi importarlo nel tuo file JavaScript.

ts
import "./styles.css";
import "./more-styles.css";

Questo genera ./app.css e ./app.js nella directory di output. Tutti i file CSS importati da JavaScript saranno bundlati in un singolo file CSS per entry point. Se importi lo stesso file CSS da multiple file JavaScript, sarà incluso solo una volta nel file CSS di output.

Plugin

Il dev server supporta plugin.

Tailwind CSS

Per usare TailwindCSS, installa il plugin bun-plugin-tailwind:

bash
# O qualsiasi client npm
bun install --dev bun-plugin-tailwind

Poi, aggiungi il plugin al tuo bunfig.toml:

bunfig.toml
toml
[serve.static]
plugins = ["bun-plugin-tailwind"]

Poi, referenzia TailwindCSS nel tuo HTML tramite tag <link>, @import in CSS, o import in JavaScript.

html
<!-- Referenzia TailwindCSS nel tuo HTML -->
<link rel="stylesheet" href="tailwindcss" />
styles.css
css
@import "tailwindcss";
ts
import "tailwindcss";

Variabili d'ambiente inline

Bun può rimpiazzare riferimenti process.env.* nel tuo JavaScript e TypeScript con i loro valori effettivi a build time. Questo è utile per iniettare configurazione come URL API o feature flag nel tuo codice frontend.

Dev server (runtime)

Per inlinare variabili d'ambiente quando usi bun ./index.html, configura l'opzione env nel tuo bunfig.toml:

bunfig.toml
toml
[serve.static]
env = "PUBLIC_*"  # solo variabili env che iniziano con PUBLIC_ (raccomandato)
# env = "inline"  # inline tutte le variabili d'ambiente
# env = "disable" # disabilita rimpiazzo variabili env (default)

NOTE

Questo funziona solo con riferimenti letterali `process.env.FOO`, non `import.meta.env` o accesso indiretto come `const env = process.env; env.FOO`.

Se una variabile d'ambiente non è impostata, potresti vedere errori runtime come ReferenceError: process is not defined nel browser.

Poi esegui il dev server:

bash
PUBLIC_API_URL=https://api.example.com bun ./index.html

Build per produzione

Quando buildi HTML statico per produzione, usa l'opzione env per inlinare variabili d'ambiente:

bash
# Inline tutte le variabili d'ambiente
bun build ./index.html --outdir=dist --env=inline

# Solo variabili env con un prefisso specifico (raccomandato)
bun build ./index.html --outdir=dist --env=PUBLIC_*
ts
// Inline tutte le variabili d'ambiente
await Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  env: "inline", 
});

// Solo variabili env con un prefisso specifico (raccomandato)
await Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  env: "PUBLIC_*", 
});

Esempio

Dato questo file sorgente:

ts
const apiUrl = process.env.PUBLIC_API_URL;
console.log(`API URL: ${apiUrl}`);

Ed eseguendo con PUBLIC_API_URL=https://api.example.com:

bash
PUBLIC_API_URL=https://api.example.com bun build ./index.html --outdir=dist --env=PUBLIC_*

L'output bundled conterrà:

dist/app.js
js
const apiUrl = "https://api.example.com";
console.log(`API URL: ${apiUrl}`);

Echo console log dal browser al terminale

Il dev server di Bun supporta lo streaming di console log dal browser al terminale.

Per abilitare, passa il flag CLI --console.

bash
bun ./index.html --console
Bun v1.3.3
ready in 6.62ms
→ http://localhost:3000/
Premi h + Enter per mostrare scorciatoie

Ogni chiamata a console.log o console.error sarà broadcast al terminale che ha avviato il server. Questo è utile per vedere errori dal browser nello stesso posto dove esegui il tuo server. Questo è anche utile per agenti AI che guardano l'output del terminale.

Internamente, questo riutilizza la connessione WebSocket esistente da hot module reloading per inviare i log.

Modificare file nel browser

Il dev server frontend di Bun ha supporto per Automatic Workspace Folders in Chrome DevTools, che ti permette di salvare modifiche ai file nel browser.

Scorciatoie Tastiera

Mentre il server è in esecuzione:

  • o + Enter - Apri nel browser
  • c + Enter - Pulisci console
  • q + Enter (o Ctrl+C) - Esci dal server

Build per Produzione

Quando sei pronto per il deploy, usa bun build per creare bundle di produzione ottimizzati:

bash
bun build ./index.html --minify --outdir=dist
ts
await Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  minify: true,
});

Watch Mode

Puoi eseguire bun build --watch per watchare cambiamenti e rebuildare automaticamente. Questo funziona bene per sviluppo librerie.

API Plugin

Hai bisogno di più controllo? Configura il bundler tramite l'API JavaScript e usa HTMLRewriter builtin di Bun per preprocessare HTML.

ts
await Bun.build({
  entrypoints: ["./index.html"],
  outdir: "./dist",
  minify: true,

  plugins: [
    {
      // Un plugin che rende ogni tag HTML minuscolo
      name: "lowercase-html-plugin",
      setup({ onLoad }) {
        const rewriter = new HTMLRewriter().on("*", {
          element(element) {
            element.tagName = element.tagName.toLowerCase();
          },
          text(element) {
            element.replace(element.text.toLowerCase());
          },
        });

        onLoad({ filter: /\.html$/ }, async args => {
          const html = await Bun.file(args.path).text();

          return {
            // Il bundler di Bun scannerà l'HTML per tag <script>, tag <link rel="stylesheet"> e altri asset
            // e li bundlerà automaticamente
            contents: rewriter.transform(html),
            loader: "html",
          };
        });
      },
    },
  ],
});

Cosa Viene Elaborato?

Bun gestisce automaticamente tutti i comuni asset web:

  • Script (<script src>) sono eseguiti attraverso il bundler JavaScript/TypeScript/JSX di Bun
  • Fogli di stile (<link rel="stylesheet">) sono eseguiti attraverso il parser CSS & bundler di Bun
  • Immagini (<img>, <picture>) sono copiate e hashate
  • Media (<video>, <audio>, <source>) sono copiati e hashati
  • Qualsiasi tag <link> con un attributo href che punta a un file locale è riscritto al nuovo percorso e hashato

Tutti i percorsi sono risolti relativamente al tuo file HTML, rendendo facile organizzare il tuo progetto come vuoi.

Come funziona

Questo è un piccolo wrapper attorno al supporto di Bun per import HTML in JavaScript.

Aggiungere un backend al tuo frontend

Per aggiungere un backend al tuo frontend, puoi usare l'opzione "routes" in Bun.serve.

Scopri di più nella documentazione full-stack.

Bun a cura di www.bunjs.com.cn