Skip to content

Bun plugins in Hamur

Hamur builds with Bun.build and serves hamur dev through Bun's dev bundler, so a Bun plugin is the lowest-level way to change what an import means: resolve a specifier, load a file, or turn one file type into JavaScript. Bun's plugin API is a subset of esbuild's, and many esbuild plugins work with it unchanged. This page says where a plugin of yours runs in Hamur, what wins when two plugins answer, and what a plugin costs.

For a change to the code of a module, prefer addTransform: it runs in the transform chain, after the loader, and costs no extra pass over each file. Reach for a Bun plugin when the file needs a loader or a resolver of its own, or when the plugin already exists for Bun or esbuild.

Where a plugin runs

You add a plugin in one of two ways, and both end up in the same list:

ts
import type { BunPlugin } from "bun"
import { defineConfig } from "hamur"

const stage: BunPlugin = {
  name: "stage",
  setup(builder) {
    builder.onResolve({ filter: /^stage$/ }, (args) => ({ path: args.path, namespace: "stage" }))
    builder.onLoad({ filter: /.*/, namespace: "stage" }, () => ({
      contents: `export default ${JSON.stringify(process.env.STAGE ?? "local")};`,
      loader: "js",
    }))
  },
}

export default defineConfig({
  framework: "react",
  build: { plugins: [stage] },
})
  • build.plugins in hamur.config.ts: an array of Bun plugins for every build.
  • addBunPlugin(plugin, options?) in a module: the same, with client and server (both default true), include and exclude (a RegExp each) and apply ("dev" or "build").
ts
import type { BunPlugin } from "bun"
import { addBunPlugin, defineModule } from "hamur/kit"

const glsl: BunPlugin = {
  name: "glsl-text",
  setup(builder) {
    builder.onResolve({ filter: /\.glsl$/ }, ({ path, resolveDir }) => ({ path: Bun.resolveSync(path, resolveDir) }))
    builder.onLoad({ filter: /\.glsl$/ }, async ({ path }) => ({
      contents: await Bun.file(path).text(),
      loader: "text",
    }))
  },
}

export default defineModule({
  meta: { name: "glsl" },
  setup() {
    addBunPlugin(glsl, { server: false, exclude: /node_modules/ })
    addBunPlugin(
      { name: "build-only-report", setup: (builder) => void builder.onEnd(() => undefined) },
      { apply: "build" },
    )
  },
})

There are four builds a plugin can be part of, and a fifth that copies the client's:

BuildA plugin from build.plugins or addBunPlugin(plugin)addBunPlugin(plugin, { server: false })addBunPlugin(plugin, { client: false })
hamur build, clientrunsrunsdoes not run
hamur build, serverrunsdoes not runruns
hamur dev, client (Bun's dev bundler)runsrunsdoes not run
hamur dev, server (the SSR build)runsdoes not rundoes not run
web workers (hamur build and hamur dev)the client's plugins, then build.worker.pluginsthe samedoes not run

The hamur dev server build takes the plugins of build.plugins only, so a plugin added with client: false reaches the production server build and not the dev one; add it without options to have it in both. A call to addBunPlugin after setup (from a build hook) takes the same route as client: false for the server, since build.plugins is frozen by then. apply: "build" keeps a plugin out of both dev builds and apply: "dev" out of hamur build; both are decided when addBunPlugin is called.

A plugin that is added to both sides goes into the list once, in the order its module ran: plugins of build.plugins first, then the ones modules add, in module order. Tests: tests/bun-plugins.test.ts ("a plugin of build.plugins comes before one added with addBunPlugin", "addBunPlugin with server: false runs in the client build only, and with client: false in the server build only"), packages/hamur/src/kit/kit.test.ts (apply, include and exclude).

Hamur's own plugins sit around yours. In a production client build the list is, first to last: the sqlite guard, then hamur-query, hamur-wasm and hamur-assets, the import guard, the virtual files, the adapter's plugins, your plugins, then Hamur's peer-dependency resolver, its imports plugin (the ~/ and @/ errors and CSS @import "#…"), and the three guards that refuse a CSS preprocessor file, a file with no loader and a query nobody resolved. The guards come last on purpose: a plugin of yours that resolves ./post.mdx or ./logo.svg?react runs first, and the guards refuse only what no plugin took. A plugin for a file type Bun has no loader for therefore needs an onResolve for it as well as an onLoad, as the .glsl plugin above has. Every onLoad result, and every file no plugin loads, then goes through the transform chain.

A plugin that a build:client:config or build:server:config hook pushes onto config.plugins comes after Hamur's imports plugin and before the three guards, and the transform chain does not see its results.

First answer wins

Bun asks the plugins that match a file in order, and the first one that returns something other than undefined loads it; the plugins after it are not asked. A plugin that returns undefined passes.

So the order above matters. Hamur's hamur-query, hamur-wasm and hamur-assets answer before yours for queries, .wasm files and asset extensions, an adapter answers for .vue and .svelte, and a plugin of build.plugins answers before one a module added. If two plugins load the same virtual module, the earlier one wins and the later one never runs for it.

tests/bun-plugins.test.ts: "when several plugins load a module, the first answer wins and a plugin that returns undefined passes it on".

onResolve filters

onResolve({ filter, namespace }) is called for a specifier only when filter matches it; Bun tests the filter before it calls into JavaScript. Give the filter the narrowest regular expression that works, as in /^stage$/ or /^virtual:/, and never /.*/. There are two reasons:

  • A callback whose filter does not match costs nothing, and one that matches costs a call per import. See what a plugin costs.
  • Under hamur dev, Bun 1.4.4's dev bundler reloads a module on every hot update, instead of replacing it and keeping its state, once any onResolve matched one of its imports (oven-sh/bun#19951). A broad onResolve therefore turns state-preserving HMR off for every module it matched. fromVite logs this once per plugin; a plugin of your own gets no such line.

include and exclude of addBunPlugin are not filters in this sense: they wrap your callback, so Bun has already crossed into JavaScript when they run. Put the narrowing in filter; use include and exclude for what a regular expression on the specifier cannot say, since they test the importer's path for onResolve and the file's path for onLoad.

tests/bun-plugins.test.ts: "an onResolve filter keeps the callback away from every other specifier".

.defer()

onLoad gets a defer function. await defer() returns once Bun has loaded every other module of the build, so a plugin can load a file whose contents depend on the rest, such as a report of every file that was loaded. Call it once per onLoad callback.

ts
import { basename } from "node:path"
import type { BunPlugin } from "bun"

const loaded: string[] = []

export const stats: BunPlugin = {
  name: "stats",
  setup(builder) {
    builder.onLoad({ filter: /\.ts$/ }, ({ path }) => {
      loaded.push(basename(path))
      return undefined
    })
    builder.onLoad({ filter: /stats\.json$/ }, async ({ defer }) => {
      await defer()
      return { contents: JSON.stringify([...loaded].sort()), loader: "json" }
    })
  },
}

Hamur's transform chain wraps a plugin's onLoad and hands the arguments through unchanged, so defer works in build.plugins and addBunPlugin. Test: tests/bun-plugins.test.ts, "defer() holds an onLoad until Bun has loaded every other module".

esbuild plugins

Bun implements onStart, onEnd, onResolve and onLoad of the esbuild plugin API, with the fields filter, namespace, path, importer, resolveDir, kind, external, contents and loader. It does not implement onDispose, resolve, pluginData, suffix, errors and warnings of a result, watchFiles and watchDirs, and initialOptions is read-only with a subset of the options (build.config is the same thing in Bun's format). A plugin that stays inside that list runs in Hamur as it does in Bun.build:

  • build.plugins: [plugin] takes it as written.
  • It runs in the client and the server build, and onStart and onEnd are called once per build.

Test: tests/bun-plugins.test.ts, "a plugin written for esbuild's four hooks runs in the client and the server build". That test uses a plugin written to esbuild's API; no esbuild plugin from npm is installed in the repository, so a given one is not tested here and may use a field Bun lacks. Try it in a build before you rely on it. For a Vite plugin use @hamur/vite-compat instead, which has a tested list.

onBeforeParse needs a native plugin

Bun's onBeforeParse hook runs before the bundler parses a file, and Bun can call it from any thread, so it is not a JavaScript callback: builder.onBeforeParse({ filter, namespace }, { napiModule, symbol }) takes a native addon, a NAPI module that exports a thread-safe C ABI function (Bun documents a Rust crate for writing one). A plugin that needs it must ship that addon. Hamur passes the plugin through to Bun; addBunPlugin's include and exclude do not filter onBeforeParse, and the transform chain, which wraps onLoad results, does not see what it does. Hamur has no test for it. Bun says a native plugin runs on several threads and skips the conversion of text to JavaScript strings, so it makes no JavaScript crossing.

What a plugin costs

A crossing is Bun calling a JavaScript plugin callback. Bun is multi-threaded and matches filters natively, but a callback runs on one thread, so each file that matches a plugin's onLoad filter costs one crossing, and a plugin that returns undefined costs it too.

Hamur keeps its own plugins to one crossing per source file in a build side. Yours are not merged into that: addBunPlugin and build.plugins plugins keep their own crossings, and each matching file costs one more. include and exclude test after the crossing, so they do not remove it. A plugin with filter: /\.tsx$/ crosses once per .tsx file in each build it is part of.

How much: with nothing done inside the callback, each extra onLoad that matches every file added about 0.19 s to a client and a server build together at 10,000 components, about 10 microseconds per file and side (measured on a Namespace runner of 8 cores with Bun 1.4.4: 0.55 s for a plain client and server build, 0.62 s with one no-op onLoad and 1.56 s with six). That is the cost of the call alone; the work inside is yours. The figure is information, not a target: it says that a plugin whose filter names the files it needs is free for the others, and one that matches every file is not.

So:

  • Name the files in filter, such as /\.glsl$/, rather than matching everything and checking inside.
  • Use namespace for virtual modules so Bun does not ask you about files.
  • If the change is a rewrite of code Hamur already loads, use addTransform: it runs in the transform chain's own pass.