# Vite plugins

`@hamur/vite-compat` runs the Rollup-hook part of a Vite plugin inside Hamur's build and `hamur dev`: `resolveId`, `load`, `transform`, `config`, `configResolved`, `buildStart`, `buildEnd` and `closeBundle`. It does not import `vite`, bundle Rollup or Rolldown, keep a module graph, or run Vite's dev server, so a plugin that lives in those parts does only what the rest of its hooks do.

```sh
bun add @hamur/vite-compat
```

Wrap the plugin with `fromVite` and put the result in `modules`. A plugin from npm works the same way: `fromVite(svgr())`. `fromVite` takes one plugin or a list, nested lists and promises included, and skips `false`, `null` and `undefined`, as Vite does.

````ts [vite-compat/config.ts]
import { defineConfig } from "hamur"
import { fromVite, type VitePluginLike } from "@hamur/vite-compat"

const buildInfo: VitePluginLike = {
  name: "build-info",
  resolveId: { filter: { id: /^virtual:build-info$/ }, handler: (id: string) => `\0${id}` },
  load: (id: string) =>
    id === "\0virtual:build-info" ? `export default ${JSON.stringify({ builtAt: new Date().toISOString() })};` : null,
}

const markdown: VitePluginLike = {
  name: "markdown",
  transform: {
    filter: { id: /\.md$/ },
    handler: (code: string) => `export default ${JSON.stringify(code)};`,
  },
}

export default defineConfig({
  framework: "react",
  modules: [fromVite([buildInfo, markdown])],
})
````

## What each hook becomes

| Vite / Rollup                          | In Hamur                                                                                                                                                                                                                                                                                                                                                                             |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `enforce: "pre" \| "post"`             | the plugin's place: `pre` plugins first, then the rest, then `post`, each in the order given. A hook object's `order` moves that one hook                                                                                                                                                                                                                                            |
| `apply: "serve" \| "build" \| fn`      | `serve` runs only under `hamur dev`, `build` only under `hamur build`; a function is called once with the config view and `{ command, mode }`                                                                                                                                                                                                                                        |
| `config(config, env)`                  | called once while the module is set up. Of the partial config it returns, `define` is added to `build.define`, a key the app already sets keeping the app's value. Any other key, `resolve.alias` included (Hamur has no alias: the app's import paths are `package.json` `imports`), logs `[hamur] vite plugin "<name>": config() returned optimizeDeps, which Hamur does not read` |
| `configResolved(config)`               | called after every plugin's `config`, with a frozen view: `root`, `base` (`app.baseURL`), `mode`, `command` (`"serve"` or `"build"`), `isProduction`, `build.outDir` (`outputDir`), `build.assetsDir`, `build.sourcemap`, `define` and `resolve.alias`                                                                                                                               |
| `buildStart()`                         | the `build:before` hook; under `hamur dev`, once before the first build                                                                                                                                                                                                                                                                                                              |
| `resolveId(source, importer, { ssr })` | a Bun `onResolve` in the plugin's place. An absolute path is a file; an id starting with `\0`, or any other id that is not a path, is a module of namespace `vite`; `false` and `{ id, external: true }` are external; `null` passes on                                                                                                                                              |
| `load(id, { ssr })`                    | a Bun `onLoad` for the `vite` namespace, and for files when the hook has a filter. The loader comes from the id's extension: `.css` is CSS, `.ts`, `.tsx` and `.jsx` their own, anything else JavaScript                                                                                                                                                                             |
| `transform(code, id, { ssr })`         | a step of the [transform chain](/modules#transform-sources) (`addTransform`), named `vite:<name>`. Without a hook filter it sees every module, as in Vite                                                                                                                                                                                                                            |
| `buildEnd()`, `closeBundle()`          | the `build:done` and `close` hooks (both at `close` under `hamur dev`); they get no error argument                                                                                                                                                                                                                                                                                   |

`ssr` is true in the server build. The id a hook sees is the file's path, `\0<id>` for a module of namespace `vite`, and `\0<namespace>:<path>` for one of Hamur's own generated modules, which most plugins skip.

Hook filters (Vite 6.3) work: `{ handler, filter: { id, code } }`, where `id` and `code` are a `RegExp`, a string, a list, or `{ include, exclude }`. An id string is a glob (`**/*.svg`, or `content/*.md` from the app's root), a code string a substring. A filter of plain `RegExp`s also narrows Bun's own filter, so the hook is not called for other imports at all.

## The code a transform sees

A plugin without `enforce: "pre"` gets the module as JavaScript: TypeScript is stripped and JSX compiled with the adapter's settings, as Vite's esbuild step does before such a plugin, and the result is a JavaScript module. A `pre` plugin gets the source as written. A transform that turns a file that is not code (`.md`, `.svg`) into code makes it a JavaScript module.

## The plugin context

| `this.`                                         | In Hamur                                                                                                                                                      |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `emitFile({ type: "asset", name, source })`     | an asset named by its content below `app.buildAssetsDir`; `getFileName(ref)` is its path below `app.baseURL`, such as `_hamur/logo-1a2b3c4d.svg`              |
| `emitFile({ type: "asset", fileName, source })` | a public file at `/<fileName>`                                                                                                                                |
| `resolve(source, importer)`                     | Bun's resolver from the importer's folder, which reads `package.json` `imports`: `{ id, external: false }` or `null`. Other plugins' `resolveId` is not asked |
| `warn(message)`, `error(message)`               | a warning under the `vite:<name>` logger; `error` throws `vite plugin "<name>": <message>`, which fails the build                                             |
| `addWatchFile(file)`                            | under `hamur dev`, a change of `file` loads the module that asked again; from `config`, `configResolved` or `buildStart` it restarts `hamur dev`              |
| `meta.watchMode`                                | `true` under `hamur dev`                                                                                                                                      |

````ts [vite-compat/plugin-context.ts]
import { fromVite } from "@hamur/vite-compat"

interface Context {
  emitFile(file: { type: "asset"; name: string; source: string }): string
  getFileName(referenceId: string): string
  warn(message: string): void
}

let outDir = ""

export default fromVite({
  name: "logo",
  enforce: "pre",
  apply: "build",
  config: () => ({ define: { __LOGO_VERSION__: JSON.stringify("2") } }),
  configResolved(config: { build: { outDir: string } }) {
    outDir = config.build.outDir
  },
  buildStart(this: Context) {
    const ref = this.emitFile({ type: "asset", name: "logo.svg", source: `<svg xmlns="http://www.w3.org/2000/svg"/>` })
    this.warn(`logo at /${this.getFileName(ref)}, written to ${outDir}`)
  },
})
````

An asset emitted from `buildStart` is written with the other public files; one emitted from `resolveId`, `load` or `transform` too, and `hamur dev` serves it from memory.

## What does not run

`configureServer`, `configurePreviewServer`, `transformIndexHtml`, `handleHotUpdate`, `hotUpdate`, `options`, `outputOptions`, `renderStart`, `renderChunk`, `generateBundle`, `writeBundle`, `augmentChunkHash`, `banner`, `footer`, `intro`, `outro`, `moduleParsed`, `resolveDynamicImport`, `resolveFileUrl`, `resolveImportMeta`, `renderDynamicImport`, `shouldTransformCachedModule`, `watchChange` and `closeWatcher` are not run. A plugin that has one logs one line per hook, and the build goes on:

```text
[hamur] vite plugin "unocss:global": transformIndexHtml is not run by @hamur/vite-compat
```

`this.getModuleInfo`, `this.getModuleIds`, `this.parse`, `this.load`, `this.setAssetSource` and `this.emitFile({ type: "chunk" })` throw when called: `vite plugin "<name>": this.parse is not available in @hamur/vite-compat`.

A plugin that imports `vite` itself at run time (for a helper such as `transformWithEsbuild`) needs `vite` installed in the app; Hamur neither installs nor imports it.

## Hot updates under `hamur dev`

A `resolveId` without a hook filter is asked about every import. Bun's dev bundler then reloads a module on each hot update instead of keeping its state, so `fromVite` logs once per plugin:

```text
[hamur] vite plugin "x" resolves every import; Bun's dev bundler then reloads every module on each hot update. A resolveId hook filter avoids it
```

Give the hook a filter, `resolveId: { filter: { id: /^virtual:/ }, handler }`, and the other modules keep their state.

## Plugins that were tried

Each row is a fixture in `tests/fixtures/vite-compat-*`, built with the bun preset and run under `hamur dev`; the plugin is a devDependency of its fixture only, and the tests are in `tests/vite-compat-fixtures.test.ts`. "Works" means the page renders what the plugin produced, in the build and under `hamur dev`. "Fails" means the test asserts the failure.

| Plugin                       | `hamur build` | `hamur dev` | What limits it                                                                                                                                                                                                                                                                      |
| ---------------------------- | ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unplugin-icons/vite` 24.0.0 | works         | works       | nothing; the app installs an icon collection such as `@iconify-json/lucide` and, for `compiler: "jsx"`, `@svgr/core` and `@svgr/plugin-jsx`                                                                                                                                         |
| `@mdx-js/rollup` 3.1.1       | works         | works       | nothing; `rollup` is its peer, and it imports none at run time                                                                                                                                                                                                                      |
| `@unocss/vite` 66.13.0       | fails         | partial     | the build stops in `configResolved`, which reads `config.build.rollupOptions`, and the CSS is made in `renderChunk`, which is not run. `hamur dev` starts and logs `configureServer` and `transformIndexHtml` as not run, so no CSS reaches the page and there is no CSS hot update |
| `vite-plugin-svgr` 5.2.0     | fails         | fails       | the plugin imports `vite`, which throws under Bun 1.4.4 (`First argument must be an Error object`, from `Error.captureStackTrace`). The error names the plugin. It waits on Bun; the test imports `vite` and fails when that stops throwing, as the cue to turn the row to works    |

`@mdx-js/rollup` and `vite-plugin-svgr` import a file type that Bun has no loader for (`./post.mdx`) or a query Hamur does not know (`./logo.svg?react`). Hamur refuses both unless a plugin takes them, so `fromVite` lets a plugin claim such an import through its `load` or `transform`; see [`fromVite`](/api-reference/vite-compat#imports-a-plugin-claims).
