Skip to content

Il bundler di Bun implementa un insieme di loader default out of the box.

Come regola generale: il bundler e il runtime supportano entrambi lo stesso insieme di tipi di file out of the box.

.js .cjs .mjs .mts .cts .ts .tsx .jsx .css .json .jsonc .toml .yaml .yml .txt .wasm .node .html .sh

Bun usa l'estensione del file per determinare quale loader built-in dovrebbe essere usato per parsare il file. Ogni loader ha un nome, come js, tsx, o json. Questi nomi sono usati quando si costruiscono plugin che estendono Bun con loader custom.

Puoi specificare esplicitamente quale loader usare usando l'attributo di import 'type'.

index.ts
ts
import my_toml from "./my_file" with { type: "toml" };
// o con import dinamici
const { default: my_toml } = await import("./my_file", { with: { type: "toml" } });

Loader built-in

js

Loader JavaScript. Default per .cjs e .mjs.

Parsa il codice e applica un insieme di trasformazioni default come dead-code elimination e tree shaking. Nota che Bun non tenta di down-convertire la sintassi al momento.


jsx

Loader JavaScript + JSX. Default per .js e .jsx.

Uguale al loader js, ma la sintassi JSX è supportata. Di default, JSX è down-convertito a JavaScript plain; i dettagli di come questo è fatto dipendono dalle opzioni di compilazione jsx* nel tuo tsconfig.json. Referenzia la documentazione TypeScript su JSX per maggiori informazioni.


ts

Loader TypeScript. Default per .ts, .mts, e .cts.

Rimuove tutta la sintassi TypeScript, poi si comporta identicamente al loader js. Bun non esegue typechecking.


tsx

Loader TypeScript + JSX. Default per .tsx.

Transpila sia TypeScript che JSX a JavaScript vanilla.


json

Loader JSON. Default per .json.

I file JSON possono essere direttamente importati.

js
import pkg from "./package.json";
pkg.name; // => "my-package"

Durante il bundling, il JSON parsato è inlinato nel bundle come un oggetto JavaScript.

js
const pkg = {
  name: "my-package",
  // ... altri campi
};

pkg.name;

Se un file .json è passato come entrypoint al bundler, sarà convertito a un modulo .js che fa export default dell'oggetto parsato.

json
{
  "name": "John Doe",
  "age": 35,
  "email": "johndoe@example.com"
}
js
export default {
  name: "John Doe",
  age: 35,
  email: "johndoe@example.com",
};

jsonc

Loader JSON con Commenti. Default per .jsonc.

I file JSONC (JSON con Commenti) possono essere direttamente importati. Bun li parserà, rimuovendo commenti e trailing commas.

js
import config from "./config.jsonc";
console.log(config);

Durante il bundling, il JSONC parsato è inlinato nel bundle come un oggetto JavaScript, identico al loader json.

js
var config = {
  option: "value",
};

NOTE

Bun usa automaticamente il loader `jsonc` per file `tsconfig.json`, `jsconfig.json`, `package.json`, e `bun.lock`.

toml

Loader TOML. Default per .toml.

I file TOML possono essere direttamente importati. Bun li parserà con il suo veloce parser TOML nativo.

js
import config from "./bunfig.toml";
config.logLevel; // => "debug"

// tramite attributo import:
// import myCustomTOML from './my.config' with {type: "toml"};

Durante il bundling, il TOML parsato è inlinato nel bundle come un oggetto JavaScript.

js
var config = {
  logLevel: "debug",
  // ...altri campi
};
config.logLevel;

Se un file .toml è passato come entrypoint, sarà convertito a un modulo .js che fa export default dell'oggetto parsato.

toml
name = "John Doe"
age = 35
email = "johndoe@example.com"
js
export default {
  name: "John Doe",
  age: 35,
  email: "johndoe@example.com",
};

yaml

Loader YAML. Default per .yaml e .yml.

I file YAML possono essere direttamente importati. Bun li parserà con il suo veloce parser YAML nativo.

js
import config from "./config.yaml";
console.log(config);

// tramite attributo import:
import data from "./data.txt" with { type: "yaml" };

Durante il bundling, il YAML parsato è inlinato nel bundle come un oggetto JavaScript.

js
var config = {
  name: "my-app",
  version: "1.0.0",
  // ...altri campi
};

Se un file .yaml o .yml è passato come entrypoint, sarà convertito a un modulo .js che fa export default dell'oggetto parsato.

yaml
name: John Doe
age: 35
email: johndoe@example.com
js
export default {
  name: "John Doe",
  age: 35,
  email: "johndoe@example.com",
};

text

Loader testo. Default per .txt.

Il contenuto del file di testo è letto e inlinato nel bundle come una stringa. I file di testo possono essere direttamente importati. Il file è letto e restituito come stringa.

js
import contents from "./file.txt";
console.log(contents); // => "Hello, world!"

// Per importare un file html come testo
// L'attributo "type" può essere usato per sovrascrivere il loader default.
import html from "./index.html" with { type: "text" };

Quando referenziato durante una build, il contenuto è inlinato nel bundle come una stringa.

js
var contents = `Hello, world!`;
console.log(contents);

Se un file .txt è passato come entrypoint, sarà convertito a un modulo .js che fa export default del contenuto del file.

txt
Hello, world!
js
export default "Hello, world!";

napi

Loader addon nativo. Default per .node.

Nel runtime, gli addon nativi possono essere direttamente importati.

js
import addon from "./addon.node";
console.log(addon);

NOTE

Nel bundler, i file `.node` sono gestiti usando il file loader.

sqlite

Loader SQLite. Richiede attributo import with { "type": "sqlite" }.

Nel runtime e bundler, i database SQLite possono essere direttamente importati. Questo caricherà il database usando bun:sqlite.

js
import db from "./my.db" with { type: "sqlite" };

Di default, il database è esterno al bundle (così che puoi potenzialmente usare un database caricato altrove), quindi il file database su-disco non sarà bundled nell'output finale.

Puoi cambiare questo comportamento con l'attributo "embed":

js
// embedda il database nel bundle
import db from "./my.db" with { type: "sqlite", embed: "true" };

html

Loader HTML. Default per .html.

Il loader html processa file HTML e bundla qualsiasi asset referenziato. Farà:

  • Bundle e hash di file JavaScript referenziati (<script src="...">)
  • Bundle e hash di file CSS referenziati (<link rel="stylesheet" href="...">)
  • Hash di immagini referenziate (<img src="...">)
  • Preserva URL esterni (di default, qualsiasi cosa che inizia con http:// o https://)

Per esempio, dato questo file HTML:

src/index.html
html
<!DOCTYPE html>
<html>
  <body>
    <img src="./image.jpg" alt="Immagine locale" />
    <img src="https://example.com/image.jpg" alt="Immagine esterna" />
    <script type="module" src="./script.js"></script>
  </body>
</html>

Outputterà un nuovo file HTML con gli asset bundled:

dist/index.html
html
<!DOCTYPE html>
<html>
  <body>
    <img src="./image-HASHED.jpg" alt="Immagine locale" />
    <img src="https://example.com/image.jpg" alt="Immagine esterna" />
    <script type="module" src="./output-ALSO-HASHED.js"></script>
  </body>
</html>

Sotto il cofano, usa lol-html per estrarre tag script e link come entrypoint, e altri asset come esterni.

Lista di selettori HTML supportati

Attualmente, la lista di selettori è:

  • audio[src]
  • iframe[src]
  • img[src]
  • img[srcset]
  • link:not([rel~='stylesheet']):not([rel~='modulepreload']):not([rel~='manifest']):not([rel~='icon']):not([rel~='apple-touch-icon'])[href]
  • link[as='font'][href], link[type^='font/'][href]
  • link[as='image'][href]
  • link[as='style'][href]
  • link[as='video'][href], link[as='audio'][href]
  • link[as='worker'][href]
  • link[rel='icon'][href], link[rel='apple-touch-icon'][href]
  • link[rel='manifest'][href]
  • link[rel='stylesheet'][href]
  • script[src]
  • source[src]
  • source[srcset]
  • video[poster]
  • video[src]

NOTE

Comportamento del Loader HTML in Contesti Differenti

Il loader html si comporta diversamente dipendendo da come è usato:

  • Build Statica: Quando esegui bun build ./index.html, Bun produce un sito statico con tutti gli asset bundled e hashati.
  • Runtime: Quando esegui bun run server.ts (dove server.ts importa un file HTML), Bun bundla gli asset on-the-fly durante lo sviluppo, abilitando funzionalità come hot module replacement.
  • Build Full-stack: Quando esegui bun build --target=bun server.ts (dove server.ts importa un file HTML), l'import risolve a un oggetto manifest che Bun.serve usa per servire efficientemente asset pre-bundled in produzione.

css

Loader CSS. Default per .css.

I file CSS possono essere direttamente importati. Il bundler parserà e bundlerà file CSS, gestendo statement @import e riferimenti url().

js
import "./styles.css";

Durante il bundling, tutti i file CSS importati sono bundled insieme in un singolo file .css nella directory di output.

css
.my-class {
  background: url("./image.png");
}

sh

Loader Bun Shell. Default per file .sh.

Questo loader è usato per parsare script Bun Shell. È supportato solo quando si avvia Bun stesso, quindi non è disponibile nel bundler o nel runtime.

bash
bun run ./script.sh

file

File loader. Default per tutti i tipi di file non riconosciuti.

Il file loader risolve l'import come un percorso/URL al file importato. È comunemente usato per referenziare asset media o font.

js
// logo.ts
import logo from "./logo.svg";
console.log(logo);

Nel runtime, Bun controlla che il file logo.svg esista e lo converte a un percorso assoluto alla posizione di logo.svg su disco.

bash
bun run logo.ts
# Output: /percorso/al/progetto/logo.svg

Nel bundler, le cose sono leggermente diverse. Il file è copiato in outdir così com'è, e l'import è risolto come un percorso relativo puntante al file copiato.

js
// Output
var logo = "./logo.svg";
console.log(logo);

Se un valore è specificato per publicPath, l'import userà quel valore come prefisso per costruire un percorso/URL assoluto.

Public pathImport risolto
"" (default)/logo.svg
"/assets"/assets/logo.svg
"https://cdn.example.com/"https://cdn.example.com/logo.svg

NOTE

La posizione e il nome del file copiato è determinato dal valore di `naming.asset`.

Questo loader è copiato nella outdir così com'è. Il nome del file copiato è determinato usando il valore di naming.asset.

Bun a cura di www.bunjs.com.cn