skip to content

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%

answer

  1. hooks the bundler ignores
  2. before and after config resolution
  3. middleware before Vite's, or after
  4. tags land at the top of head
  5. the build has no dev server

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.

solid answer

~40 s

`config(config, { command, mode })` runs before resolution: it can return a partial config that Vite deep-merges, but plugins added there have no effect because user plugins are already resolved. `configResolved(resolved)` runs afterwards and is where a plugin stores the final `base`, `root` or `command`. `configureServer(server)` runs only for the dev server: `server.middlewares.use()` called in it puts an article-preview route ahead of Vite's own middlewares, and returning a function installs it after them, just before Vite serves `index.html`. `configurePreviewServer` does the same for `vite preview`. `transformIndexHtml` runs for HTML entries in dev and build and returns a string, tag descriptors or `{ html, tags }`; a tag goes to `head-prepend` unless `injectTo` says otherwise. `config`, `configResolved` and `transformIndexHtml` run in `vite build`; the server hooks do not.

code

typescript · 24 lines
typescript
import type { Plugin } from 'vite'
import { renderPreview } from './render-preview'

export function newsroomShell(): Plugin {
  return {
    name: 'newsroom-shell',
    configureServer(server) {
      // installed before Vite's own middlewares
      server.middlewares.use('/__article-preview', (req, res) => {
        res.setHeader('Content-Type', 'text/html')
        res.end(renderPreview(req.url ?? '/'))
      })
    },
    transformIndexHtml() {
      return [
        {
          tag: 'script',
          attrs: { src: 'https://consent.example.com/loader.js' },
          injectTo: 'head-prepend',
        },
      ]
    },
  }
}

go deeper

for a junior

Know that Vite adds its own plugin hooks beyond the bundler's, and that configureServer is where a plugin adds middleware to the dev server.

for a middle

Explain config against configResolved, the two middleware positions in configureServer, and transformIndexHtml's return forms and injectTo default, with which hooks run in vite build.

for a senior

Spot code that assumes the dev server exists during a build, pick the transformIndexHtml order a bundled script needs, and keep config hooks to returning partial config.

for a principal

Decide which cross-cutting behaviour belongs in a shared plugin's hooks and which in each app's own config, keeping dev-only middleware out of anything production depends on.

## Hooks only Vite calls Vite plugins extend the bundler's plugin interface with hooks for the dev server, the preview server and the HTML entry. The bundler itself ignores them. Knowing when each one fires is knowing where your plugin code runs. | Hook | When it runs | In `vite build`? | Typical use | |---|---|---|---| | `config` | before the config is resolved | yes | return a partial config to merge | | `configResolved` | after the config is resolved | yes | read and store the final config | | `configureServer` | when the dev server is created | no | add middleware, keep the server | | `configurePreviewServer` | when `vite preview` starts | no | middleware for the preview server | | `transformIndexHtml` | for each HTML entry such as `index.html` | yes | rewrite HTML, inject tags | | `hotUpdate` | when a watched file changes in dev | no | custom hot-update handling | `config`, `configResolved` and the two server hooks are **global**: they run once, not once per environment. `transformIndexHtml` and `hotUpdate` are per environment. ## `config` against `configResolved` - `config(userConfig, { command, mode, isSsrBuild, isPreview })` receives the raw config, with CLI options merged into the config file. Returning a partial object is the recommended form, and Vite deep-merges it; mutating the argument is the fallback when merging cannot express the change. - Plugins added inside `config` have **no effect**, because user plugins are already resolved when it runs. - `configResolved(resolved)` receives the final resolved config and returns nothing. It is where a plugin stores `resolved.base`, `resolved.root` or `resolved.command` for its later hooks. - `config` hooks run one after another in plugin order, each seeing what earlier ones merged, while `configResolved` hooks are parallel, so one plugin's `configResolved` should not depend on another's having finished. A typical pairing: `config` returns a small partial config, such as an alias that every app using the plugin should get, and `configResolved` records whether the command is `serve` or `build` so `transform` can emit preview-only code in dev. ## `configureServer`: an article-preview route `configureServer(server)` receives the dev server instance. Its most common use is `server.middlewares.use()`, which adds a connect middleware. The position follows from when you call it: 1. Called directly in the hook, the middleware is installed **before** Vite's internal middlewares, so `/__article-preview` is answered before Vite's module transforms and static files are consulted. 2. Called inside a function the hook **returns**, it is installed after Vite's internal middlewares but before Vite serves `index.html`, so it can still answer with custom content instead of the HTML page. The same hook can store `server` for other hooks, for example to reach the module graph or the WebSocket server. Because `vite build` never calls it, every other hook that uses the stored server must cope with its absence. `configurePreviewServer` follows the same pattern for `vite preview`. ## `transformIndexHtml`: the consent script The hook receives the HTML string and a context: `path` and `filename`, plus `server` in dev or `bundle` and `chunk` in a build. It may return: - a new HTML string; - an array of tag descriptors, `{ tag, attrs, children, injectTo }`; - `{ html, tags }` for both. `injectTo` accepts `'head'`, `'body'`, `'head-prepend'` or `'body-prepend'`. The default, `'head-prepend'`, suits a consent loader that must run before the application's scripts. Ordering uses the object form: - no `order`: runs after Vite has transformed the HTML, which is right for a finished external script URL; - `order: 'pre'`: runs before that, so an injected `<script type="module" src="/src/consent.ts">` goes through the plugin pipeline and gets bundled; - `order: 'post'`: runs after all hooks that have no order. A framework that handles its entry files itself may never call this hook. In a multi-page app the hook runs once for each HTML entry, so a plugin that should touch only one page checks `ctx.path` or `ctx.filename` before changing anything. ## Where code runs: the build has no server - `config`, `configResolved` and `transformIndexHtml` run under both `vite` and `vite build`. - `configureServer` and `hotUpdate` exist only while the dev server runs; `configurePreviewServer` only under `vite preview`. - None of these hooks runs in the browser; they shape what the browser receives. ## Mistakes to avoid - Returning config from `configResolved`, which ignores the return value. - Adding plugins from `config` and wondering why they never run. - Assuming a server stored in `configureServer` exists during `vite build`. - Injecting a module script with no `order: 'pre'` and expecting Vite to bundle it.

  • Why does a plugin that stores the server in configureServer and uses it in transform crash in vite build?
    `vite build` never calls `configureServer`, so the stored variable stays `undefined` while `transform` still runs for every module. Guard the use with `if (server)` or branch on the `command` read in `configResolved`. Vite's docs warn that other hooks must cope with the server's absence for exactly this reason.
  • When should transformIndexHtml use order: 'pre'?
    When the tag you inject must itself go through Vite's pipeline, for example `<script type="module" src="/src/consent.ts">`, which has to be transformed and bundled. Without an order the hook runs after Vite has processed the HTML, which suits a finished third-party script URL; `order: 'post'` runs after every hook that has no order.

  • configureServer also runs during vite build to prepare the output.
  • Plugins added inside the config hook are picked up by Vite.
  • configResolved can return a partial config to change resolved settings.
  • Middleware added in configureServer always runs after Vite's own middlewares.
  • transformIndexHtml only runs in the dev server, never in the build.