Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Bundler and Transpiler

Plugins, Macros and the Transpiler

Extend Bun with plugins (onResolve, onLoad), run them in builds and at run time, compute values at bundle time with macros, and transform or scan code with the Bun.Transpiler API.

Loaders cover the common file types, but projects always have something special: a custom file format, a virtual module that does not exist on disk, a value that must be computed while building. Bun gives you three extension points. Plugins teach the bundler and the runtime new tricks. Macros run a function at bundle time and paste its result into your code. The Bun.Transpiler API exposes the native TypeScript/JSX transformer so you can use it in your own tools. This lesson covers all three.

Bun is not available in the page runner, so the Bun code is read-only. Stand-ins using plain JavaScript model the hooks so you can see the flow.

What a plugin is

A plugin is an object with a name and a setup function. Inside setup you register hooks that run while Bun resolves and loads modules. The API is deliberately compatible with esbuild's, so many esbuild plugins work with little change.

TypeScript
import type { BunPlugin } from "bun";

const examplePlugin: BunPlugin = {
  name: "example",
  setup(build) {
    // register hooks here
    build.onResolve({ filter: /^virtual:/ }, (args) => { /* ... */ });
    build.onLoad({ filter: /\.md$/ }, async (args) => { /* ... */ });
  },
};

Two hooks matter:

Hook Question it answers
onResolve({ filter, namespace? }, callback) "Where is this import? Which file or virtual module does it mean?"
onLoad({ filter, namespace? }, callback) "What is the content of this file, and how should it be treated?"

filter is a regular expression tested against the import path (onResolve) or the file path (onLoad). Keep filters specific, because Bun calls your callback for every match.

A plugin that loads Markdown

This plugin turns .md files into modules that export their text:

TypeScript
// plugins/markdown.ts
import type { BunPlugin } from "bun";

export const markdownPlugin: BunPlugin = {
  name: "markdown-loader",
  setup(build) {
    build.onLoad({ filter: /\.md$/ }, async (args) => {
      const text = await Bun.file(args.path).text();
      return {
        contents: `export default ${JSON.stringify(text)};`,
        loader: "js",
      };
    });
  },
};

Use it in a build:

TypeScript
import { markdownPlugin } from "./plugins/markdown";

await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  plugins: [markdownPlugin],
});
TypeScript
// src/index.ts
import readme from "../README.md";
console.log(readme.length);

The callback returns an object with contents (the source code the bundler should use) and loader (how to treat that source). Returning generated JavaScript and loader: "js" is the simplest, most flexible pattern. If you return nothing (undefined), Bun falls through to the next hook or the default loader.

A virtual module

onResolve can map an import to something that is not a real file, then onLoad can supply its content in a custom namespace:

TypeScript
const virtualPlugin: BunPlugin = {
  name: "virtual-build-info",
  setup(build) {
    build.onResolve({ filter: /^virtual:build-info$/ }, (args) => ({
      path: args.path,
      namespace: "virtual",
    }));

    build.onLoad({ filter: /.*/, namespace: "virtual" }, () => ({
      contents: `export const builtAt = ${JSON.stringify(new Date().toISOString())};`,
      loader: "js",
    }));
  },
};
TypeScript
import { builtAt } from "virtual:build-info";
console.log(`Built at ${builtAt}`);

The value is computed when the build runs and baked into the bundle. This is how build timestamps, git hashes and generated route tables are often injected.

Seeing the hook flow

This stand-in implements the resolve-then-load pipeline with two plugins (a Markdown loader and a virtual module) so you can follow what happens to each import:

Node.js Stand-in: onResolve and onLoad pipeline (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.

Runtime plugins

The same plugin object also works at run time, so bun run can import .md or virtual modules without a build:

TypeScript
// preload.ts
import { plugin } from "bun";
import { markdownPlugin } from "./plugins/markdown";

plugin(markdownPlugin);

Register it as a preload in bunfig.toml so it applies to every run, including tests:

TOML
preload = ["./preload.ts"]

Now import readme from "./README.md" works under bun run, bun test and bun --watch. The bun:test runner uses the same preload, which is a convenient way to mock modules or set up globals.

Macros: code that runs at build time

A macro is a function that executes while Bun bundles (or transpiles) your code. The value it returns replaces the call. Mark the import with type: "macro":

TypeScript
// macros.ts
export function buildDate(): string {
  return new Date().toISOString();
}

export async function fetchLatestVersion(): Promise<string> {
  const response = await fetch("https://registry.npmjs.org/bun/latest");
  const data = await response.json();
  return data.version;
}
TypeScript
// index.ts
import { buildDate, fetchLatestVersion } from "./macros" with { type: "macro" };

console.log(`Built ${buildDate()}`);
console.log(`Latest Bun on npm: ${await fetchLatestVersion()}`);

After bundling, the output contains the literal date string and version string; the fetch ran on your build machine and is not in the final bundle. Macro results must be serialisable data: strings, numbers, booleans, arrays, plain objects, and Response or Blob (as data). Use them for build metadata, embedding a file's content, or precomputing a lookup table. Avoid network calls in macros unless you accept slower, less repeatable builds.

Plugin and macro support is a quickly evolving corner of Bun; check the docs for details of your version, especially around how macros interact with bun run.

Bun.Transpiler

The native transformer that powers bun run is available as a class:

TypeScript
const transpiler = new Bun.Transpiler({
  loader: "tsx",          // js, jsx, ts or tsx
  target: "browser",      // bun, node or browser
  tsconfig: { compilerOptions: { jsx: "react-jsx" } },
});

const js = transpiler.transformSync(`
  type Props = { name: string };
  const Hello = ({ name }: Props) => <h1>Hello {name}</h1>;
`);
console.log(js);

The result is JavaScript with types removed and JSX converted. There is an async transform too. This is useful for a build script, a documentation tool that previews TypeScript, or a custom dev server.

scan reads a module without running it and reports what it imports and exports:

TypeScript
const { imports, exports } = transpiler.scan(`
  import { z } from "zod";
  import "./side-effect";
  export const answer = 42;
  export function greet() {}
`);

console.log(imports);  // [{ path: "zod", kind: "import-statement" }, { path: "./side-effect", ... }]
console.log(exports);  // ["answer", "greet"]

scanImports returns only imports, and it is fast enough to analyse an entire repository. Tools use it to draw dependency graphs or find unused files.

Here is a plain-JavaScript stand-in for scan, using a pattern that handles the common import forms:

Node.js Stand-in: scan a module's imports and exports (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.

A real parser is more precise (it understands strings, comments and dynamic imports), but the output shape is the same.

Choosing the right tool

Need Use
A new file type becomes a module Plugin with onLoad
A fake module or an alias Plugin with onResolve
A value computed once at build time Macro, or a plugin that generates the module
Compile TS/JSX inside your own tool Bun.Transpiler
Same behaviour at run time and in tests Runtime plugin loaded through preload

Prefer the simplest option: often define or a loader setting from the earlier lessons is enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an onLoad hook return so the bundler can use generated code?

    Returning { contents, loader } tells Bun the source text and how to process it.
  2. 2. How do you make a plugin apply to bun run and bun test as well as builds?

    Runtime plugins are registered through Bun.plugin / plugin() and loaded as a preload script.
  3. 3. When does a macro function run?

    Macros execute during the build, and their serialised return value replaces the call.
  4. 4. What does Bun.Transpiler.scan return?

    scan analyses source and returns import and export information.

Summary

  • Plugins have a name and setup(build); onResolve maps import paths, onLoad supplies content and a loader.
  • Virtual modules use a custom namespace; generated contents with loader: "js" is the simplest pattern.
  • Register plugins at run time with plugin() in a preload file so scripts and tests behave like builds.
  • Macros (with { type: "macro" }) run at bundle time and inline their result.
  • Bun.Transpiler offers transformSync/transform and scan/scanImports for your own tools.

Next: Single-File Executables