skip to content

Plugin System

Vite plugins extend Rolldown's resolveId, load and transform hooks with Vite-only ones like configureServer and transformIndexHtml, ordered by enforce. Writing one shows where code runs.

on this pageshow

explore

questions

6

In a Vite 8 plugin, what do resolveId, load and transform each do when turning .md articles and a virtual:build-info import into modules?

level: middleimportance: must knowfreq 14%

answer

  1. an id, then code, then new code
  2. two hooks stop at the first answer
  3. transforms chain in plugin order
  4. real files resolve without help
  5. a null byte marks a virtual id

basics

~20 s

resolveId turns an import specifier into an id, load returns that id's code, and transform rewrites the loaded code. A .md article needs only transform; virtual:build-info needs resolveId to claim the id and load to supply its code.

solid answer

~40 s

`resolveId(source, importer)` maps the specifier written in an `import` to a resolved id; `load(id)` returns the code for that id; `transform(code, id)` receives loaded code and returns new code with a source map. `resolveId` and `load` stop at the first plugin that returns a value, while every matching `transform` runs in turn on the previous output. For `import article from './articles/budget-2027.md'`, Vite's resolver finds the real file and its text is read from disk, so one `transform` filtered to `/\.md$/` turns the markdown into `export default { title, html }`. For `virtual:build-info` no file exists: `resolveId` claims the id and returns `'\0virtual:build-info'`, and `load` returns the generated code. In Vite 8 the dev server calls these hooks per request and Rolldown calls them in `vite build`.

code

typescript · 25 lines
typescript
import type { Plugin } from 'vite'
import { exactRegex } from '@rolldown/pluginutils'
import { renderArticle } from './render-article'

const VIRTUAL_ID = 'virtual:build-info'
const RESOLVED_ID = '\0' + VIRTUAL_ID

export const newsroom = (): Plugin => ({
  name: 'newsroom',
  resolveId: {
    filter: { id: exactRegex(VIRTUAL_ID) },
    handler: () => RESOLVED_ID,
  },
  load: {
    filter: { id: exactRegex(RESOLVED_ID) },
    handler: () => `export const builtAt = ${JSON.stringify(new Date().toISOString())}`,
  },
  transform: {
    filter: { id: /\.md$/ },
    handler(src) {
      const code = `export default ${JSON.stringify(renderArticle(src))}`
      return { code, map: null, moduleType: 'js' }
    },
  },
})

go deeper

for a junior

Recall the order an import goes through: the specifier is resolved to an id, the id is loaded as code, and the code is transformed, in dev and in the build alike.

for a middle

Explain first-wins resolveId and load against chained transform, and write both the .md transform and the virtual:build-info pair with its null-byte resolved id.

for a senior

Show that you filter hooks so they skip unrelated modules, return source maps from transforms, and know when Vite 8 needs moduleType: 'js' on converted output.

for a principal

Decide when a team's need belongs in a virtual module or transform plugin rather than a generated file checked into the repo, weighing debuggability, caching and long-term ownership.

## Three hooks, three questions When a module imports something, Vite asks its plugins three questions in turn. The answers come from hooks Vite shares with Rolldown's plugin interface, which mirrors Rollup's. | Hook | Receives | Returns | Kind | |---|---|---|---| | `resolveId` | the specifier as written, the importer, options | a resolved id, or `null` to pass | async, **first** | | `load` | a resolved id | the module's code, optionally with a map and `moduleType`, or `null` | async, **first** | | `transform` | the loaded code and its id | new code and a source map, or `null` | async, **sequential** | - **First** means plugins are asked in order until one returns something other than `null` or `undefined`; later plugins are not asked. - **Sequential** means every plugin's `transform` runs in order, each receiving the previous plugin's result. `resolveId` and `load` therefore decide **ownership** of an id, while `transform` hooks **compose**. ## Where the hooks run During development, Vite's dev server transforms each module when the browser requests it. A plugin container calls `resolveId`, `load` and `transform` for that request the same way the bundler would. In `vite build`, Vite 8 runs **Rolldown**, which calls the same hooks while it builds the module graph and bundles it. One plugin therefore works in both modes, with some differences in dev: - it only sees the modules a page actually requests, not the whole graph; - `options` and `buildStart` run once when the server starts, and `buildEnd` and `closeBundle` when it closes; - `moduleParsed` is not called, because Vite avoids full AST parses for speed; - output-generation hooks other than `closeBundle` are not called at all; - some `resolveId` calls report the root `index.html` as the `importer`, because the true importer cannot always be known in unbundled serving. ## A `.md` article: transform only `import article from './articles/budget-2027.md'` points at a real file, so: 1. Vite's own resolver turns the relative specifier into an absolute path; no custom `resolveId` is needed. 2. No plugin claims the id in `load`, so the file's text is read from disk. 3. Your `transform`, filtered to ids ending in `.md`, receives the markdown text, renders it and returns JavaScript such as `export default { title, html }`, with a real source map or `map: null`. Vite 8's migration guide adds one detail for plugin authors. Rolldown infers each module's **module type** from its id's extension, and a hook that converts another type into JavaScript may need to return `moduleType: 'js'` so later stages treat the result as JavaScript. ## `virtual:build-info`: resolveId plus load A **virtual module** has no file behind it. By convention its user-facing id starts with `virtual:`, ideally namespaced by the plugin. The plugin: 1. claims `virtual:build-info` in `resolveId` and returns `'\0virtual:build-info'`; 2. answers `load` for that resolved id with generated code, such as `export const builtAt = "…"`. Application code imports it like any module: ```ts import { builtAt } from 'virtual:build-info' ``` The leading **null byte** (`\0`) is a convention from the Rollup ecosystem. Other plugins, such as Node-style resolution or path-filtered transforms, leave such ids alone, and source-map handling can tell them apart from real files. Because `\0` is not allowed in an import URL, the browser sees the module in dev as `/@id/__x00__virtual:build-info`; Vite decodes it before the plugin pipeline, so hooks always see `\0virtual:build-info`. Submodules derived from a real file, such as the parts of a single-file component, should not use `\0`, or their source maps stop pointing at that file. TypeScript also needs an ambient module declaration for the import to type-check. ## Filters keep hooks cheap Each hook can be written as an object `{ filter, handler }`. With `filter: { id: /\.md$/ }`, Vite skips the call for every other module instead of entering your function only to return early. `resolveId` and `load` filter on `id`; `transform` can also filter on `moduleType` and `code`. In `resolveId` the `id` filter must be a regular expression, because it is matched against the raw specifier rather than a path; `exactRegex` from `@rolldown/pluginutils` builds one for a fixed id. ## Mistakes to avoid - Writing `resolveId` for files that already exist on disk. - Returning code from `load` in two plugins and expecting both to apply. - Rewriting code in `transform` without returning a map, so debugging lands in generated output. - Writing `\0` in application imports: users import `virtual:build-info`, and only the plugin uses the prefixed id. - Assuming a virtual module's code is regenerated on every request in dev; once loaded, it is cached like any other module until something invalidates it.

  • Why does resolveId return '\0virtual:build-info' instead of the plain id?
    The `\0` prefix is the Rollup-ecosystem convention for ids that are not files. Other plugins, such as Node-style resolution or a path-filtered transform, skip them, and source-map handling can tell them apart from real files. Since `\0` cannot appear in a URL, the browser requests it in dev as `/@id/__x00__virtual:build-info`; Vite decodes that before hooks run, so `load` matches the prefixed id.
  • Two plugins both implement load for the same id; whose code does Vite use?
    The first plugin, in resolved plugin order, that returns something other than `null` or `undefined`. `load` and `resolveId` are first-wins hooks, so later plugins never see that id. `transform` is the opposite: every matching transform runs in order on the previous result. Order therefore decides ownership for `load` and composition for `transform`, and `enforce` or a hook's `order` sets that order.
  • When does a Vite 8 plugin's load or transform need to return moduleType: 'js'?
    When it converts content of another module type into JavaScript. Rolldown infers a module's type from its resolved id's extension, so a hook that turns a `.txt` or `.json` file into an ES module should declare that the result is JavaScript. Vite 8's migration guide flags this for plugin authors; a hook that only rewrites JavaScript does not need it.

resolveId and load work like a switchboard, where the first operator to pick up takes the call and nobody else hears it; transform is an assembly line, where every station works on the item in turn.

  • A .md import needs a custom resolveId before Vite can find the file.
  • Every plugin's load hook runs and Vite merges their results.
  • The transform hook runs only in vite build, never in the dev server.
  • A virtual module needs a placeholder file on disk to be importable.
  • Application code must write the null-byte prefix in its import statement.

Assumes Vite 8, where Rolldown calls these hooks in vite build and a hook that converts another module type into JavaScript may need to return moduleType: 'js'.

open as a page

In a Vite project, what does adding a framework plugin such as @vitejs/plugin-vue or @vitejs/plugin-react to the plugins array actually do?

level: juniorimportance: should knowfreq 16%

basics

~20 s

A framework plugin teaches Vite's pipeline what it cannot do alone: plugin-vue compiles .vue files into JavaScript and wires their hot updates, and plugin-react adds Fast Refresh and the automatic JSX runtime. It runs in Vite, not in the app.

open as a page

In a Vite plugin, what do the enforce and apply properties control, and where does a plugin without them run among Vite's core plugins?

level: middleimportance: should knowfreq 8%

basics

~20 s

enforce sets a plugin's tier: pre runs before Vite's core plugins, post after its build plugins, and no enforce right after the core plugins. apply keeps a plugin only for serve, for build, or where a function returns true.

open as a page

Which Vite-only plugin hooks read the final config, add dev-server middleware and inject tags into index.html, and which of them run in vite build?

level: middleimportance: should knowfreq 10%

basics

~20 s

configResolved reads the final config, configureServer adds middleware to the dev server, and transformIndexHtml injects tags into index.html. configResolved and transformIndexHtml also run in vite build; configureServer never does, so code relying on it needs a guard.

open as a page

In a Vite plugin, how does the hotUpdate hook push an edited .md article to the browser as a custom event instead of Vite's default hot update?

level: seniorimportance: should knowfreq 5%

basics

~20 s

hotUpdate runs in the dev server when a watched file is created, updated or deleted, once per environment. Returning an empty array tells Vite the plugin handled it, so the plugin sends a custom event with this.environment.hot.send for the page.

open as a page

When porting an in-house Rollup-style plugin to Vite 8, why add hook filters, when should load or transform return moduleType: 'js', and which Rollup hooks stop running?

level: seniorimportance: nice to knowfreq 3%

basics

~20 s

In Vite 8, Rolldown calls JavaScript plugins from Rust, so hook filters let it skip unrelated modules. A load or transform turning another type into JavaScript should return moduleType: 'js'. shouldTransformCachedModule, resolveImportMeta and renderDynamicImport no longer run.

open as a page