Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Bundler and Transpiler

Loaders and HTML Entry Points

Learn how Bun loaders turn JSON, TOML, text, CSS, images and WebAssembly into modules, choose loaders per extension, and bundle a whole web page starting from an HTML file.

JavaScript projects import more than JavaScript: stylesheets, images, JSON data, text templates, WebAssembly. A bundler needs a rule for each kind of file, and in Bun that rule is called a loader. A loader decides how a file is turned into a module. This lesson lists the built-in loaders, shows how to override them, covers CSS handling, and then demonstrates the neat shortcut of starting a build from an HTML file so scripts, styles and images are discovered automatically.

What a loader does

When the bundler meets import something from "./file.ext", it looks at the extension, picks a loader, and the loader produces JavaScript that represents the file. The same loaders apply when you simply bun run a file, which is why importing JSON "just works" at run time too.

Extension Loader What import x from "./file" gives
.js .mjs .cjs js JavaScript module
.jsx jsx JSX transformed to calls
.ts .mts .cts ts Types removed
.tsx tsx Types removed, JSX transformed
.json json The parsed object
.toml toml The parsed object
.yaml .yml yaml The parsed object (recent versions)
.txt text The file content as a string
.css css Bundled into a stylesheet
.html html Processed page, see below
.wasm wasm WebAssembly module
.node napi Native add-on
anything else file A path (URL) to the copied file

Typical use:

TypeScript
import pkg from "./package.json";
import config from "./config.toml";
import template from "./email.txt" with { type: "text" };
import logoUrl from "./logo.svg";   // file loader: "./logo-3f2a9c.svg" when bundled

console.log(pkg.version, config.server.port);
console.log(template.slice(0, 40));
console.log(logoUrl);               // a URL to use in <img src>

JSON and TOML become real objects at build time, so imports are fast and tree-shakeable: if you only use pkg.version, a bundler can drop the rest of the data.

Changing a loader

The file loader copies a file into the output and gives you its URL. Sometimes you want something else: embed small images directly as data URLs to save a request, or load .sql files as text.

Terminal
bun build ./src/index.ts --outdir ./dist --loader .svg:dataurl --loader .sql:text
TypeScript
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  loader: {
    ".svg": "dataurl",
    ".sql": "text",
    ".png": "file",
  },
});

Common loader names for this option: js, jsx, ts, tsx, json, toml, text, file, dataurl, base64, binary, wasm, napi.

  • text: the contents as a string.
  • file: copy and return a URL (best for large assets, cached separately).
  • dataurl: embed as data:image/svg+xml;base64,... (best for tiny icons).
  • base64: the raw base64 string.
  • binary: the bytes as a Uint8Array.

Individual imports can also pick a loader with an attribute:

TypeScript
import raw from "./query.sql" with { type: "text" };

How a loader dispatch works

Conceptually a loader table is a lookup from extension to a function. This runnable stand-in implements a miniature version for JSON, text and data URLs, which is the same idea Bun runs natively:

Node.js Stand-in: a tiny loader table (runs on Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last call shows the reason behind Bun's file fallback: any unknown extension needs a rule, and copying the file is a safe default.

CSS in the bundle

Bun understands CSS directly:

CSS
/* styles/main.css */
@import "./reset.css";

.card {
  display: grid;
  gap: 1rem;
  padding: 1rem;

  & h2 {
    margin: 0;
  }
}
TypeScript
import "./styles/main.css";

What the bundler does with it:

  • inlines @import chains into one stylesheet;
  • rewrites url(...) references to hashed asset files;
  • converts newer syntax (nesting, modern colour functions) to forms older browsers understand, based on your target;
  • minifies when --minify is on;
  • writes index.css beside index.js for the entry that imported it.

CSS Modules (files named *.module.css) give locally scoped class names:

TypeScript
import styles from "./card.module.css";

document.body.innerHTML = `<div class="${styles.card}">Hello</div>`;

Frameworks such as Tailwind add steps through a plugin; see Plugins, Macros and the Transpiler.

HTML as the entry point

For a website, the most natural entry point is the page itself. Give Bun an HTML file and it discovers everything referenced from it.

HTML
<!-- index.html -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My App</title>
    <link rel="stylesheet" href="./styles/main.css" />
  </head>
  <body>
    <div id="root"></div>
    <img src="./logo.svg" alt="Logo" />
    <script type="module" src="./src/main.tsx"></script>
  </body>
</html>
Terminal
bun build ./index.html --outdir ./dist

Bun reads the HTML, finds the <script>, <link> and <img> tags, bundles the TypeScript and CSS, copies the image, and writes a new dist/index.html whose tags point to the generated files, usually with content hashes added to the names. The script no longer says .tsx; the references are rewritten to the built output. With --minify, the HTML is minified too.

You can pass several HTML files (./index.html ./about.html) and shared code is split into common chunks automatically.

The development server

For development you do not even need to build. Run Bun on the HTML file:

Terminal
bun ./index.html

Bun starts a dev server on a local port, bundles on demand, serves the page, and reloads the browser on change. Several pages and a route per file can be served by listing them (bun ./index.html ./about.html). The server is a good fit for front-end experiments; for an API plus pages in one program, Bun.serve can import HTML files as routes, which you will see in the HTTP chapter.

TypeScript
import homepage from "./index.html";

Bun.serve({
  routes: {
    "/": homepage,          // bundled and served by Bun
    "/api/hello": () => Response.json({ hello: "world" }),
  },
});

When running (or building) this way, the same loaders and CSS handling apply, so a single import of a .tsx file from the HTML is all the configuration you need.

Troubleshooting

  • "Could not resolve ./file": the path is wrong or the extension has no loader. Check spelling and, for unusual types, add loader.
  • Image shows a broken link: with the file loader the import is a URL string. Use it as src, not as an element.
  • Large bundle: images embedded as dataurl count toward size. Use file for anything beyond icons.
  • CSS ordering: imports are inlined in the order written; place resets first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does importing a .json file give you in Bun?

    The json loader parses the file at build time, so you receive the object.
  2. 2. Which loader embeds a small image directly into the JavaScript output?

    dataurl produces a data: URL string that contains the file contents.
  3. 3. What does bun build ./index.html --outdir ./dist do?

    Bun treats the HTML as an entry point, processes its tags and writes updated output with the new file names.
  4. 4. What does the default file loader do for an unknown extension such as .png?

    Unknown extensions use the file loader, so the asset is copied and the import is its public path.

Summary

  • A loader decides how each file type becomes a module: js/ts, json, toml, text, css, html, wasm, napi, and file for everything else.
  • Override with --loader .ext:name or the loader option; with { type: "text" } works per import.
  • Use file for large assets and dataurl for tiny ones.
  • CSS is bundled, with @import inlined, url() rewritten, modern syntax lowered and CSS Modules supported.
  • An HTML file is the best entry point for a site: bun build ./index.html builds it, bun ./index.html serves it.

Next: Plugins, Macros and the Transpiler