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?
answer
- the server half of hot updates
- called once per environment
- nothing, a narrowed list, or empty
- send your own event to clients
- read() rather than a raw file read
basics
~20 shotUpdate 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.
solid answer
~40 s`hotUpdate(options)` receives `type` (`'create' | 'update' | 'delete'`), `file`, `timestamp`, the affected `modules` in the current environment, a `read()` helper and the `server`. Vite calls it once for each environment, in `server.environments` order, so a browser-only plugin starts with `if (this.environment.name !== 'client') return`. Returning nothing lets Vite's normal update run, returning a filtered list narrows it, and returning `[]` takes over. For an edited article, the plugin calls `await read()`, which avoids catching an editor mid-write, renders the markdown, sends `this.environment.hot.send({ type: 'custom', event: 'news:article-update', data })` and returns `[]`; a listener registered with `import.meta.hot.on` swaps the text without a reload. The older `handleHotUpdate` still works but runs once for all environments, and only for updates.
code
typescript · 20 linesimport type { Plugin } from 'vite'
import { renderArticle } from './render-article'
export function articleHotUpdate(): Plugin {
return {
name: 'newsroom-article-hmr',
async hotUpdate({ type, file, read }) {
if (this.environment.name !== 'client') return
if (type !== 'update' || !file.endsWith('.md')) return
const { title, html } = renderArticle(await read())
this.environment.hot.send({
type: 'custom',
event: 'news:article-update',
data: { file, title, html },
})
return []
},
}
}go deeper
Recall that plugins can react to file changes in the dev server, and that the browser side of hot updates is a separate API used by application code.
Explain the hotUpdate options, its three return choices, and how a custom event sent from the hook reaches a handler registered with import.meta.hot.on.
Guard by environment, use read() instead of a direct file read, and choose between narrowing modules, a custom event and a full reload based on what the edited file feeds.
Judge when custom hot-update handling is worth owning in a shared plugin rather than accepting a full reload, given its maintenance cost across Vite releases and environments.
When a file changes while the dev server runs, two halves cooperate. On the **server**, Vite works out which modules the file affects and what to tell the connected clients; plugins take part through `hotUpdate`. In the **browser**, application code reacts through `import.meta.hot`. This hook is the server half: the plugin decides what message, if any, reaches the page. ## What the hook receives `hotUpdate(options)` is called with `this.environment` set to the environment being processed, and `options` holds: | Field | Meaning | |---|---| | `type` | `'create'`, `'update'` or `'delete'` | | `file` | the changed file's path | | `timestamp` | when the change was seen | | `modules` | this environment's modules affected by the file; several when one file serves several modules | | `read()` | an async read of the file's current content | | `server` | the dev server instance | Vite calls the hook for each environment in turn, following `server.environments`. With a client and an SSR environment, the hook is therefore called twice for one change. A plugin that only cares about the browser starts with `if (this.environment.name !== 'client') return`, which leaves the SSR pass to Vite's default handling. ## Three ways to answer 1. **Return nothing.** Vite performs its normal update for `modules`. 2. **Return a filtered array.** The update goes ahead with only those modules, useful when you know a change affects fewer modules than Vite assumed. 3. **Return `[]`.** Vite does no update of its own, and the plugin performs one: a custom event or a full reload. The one exception is an `.html` file, which Vite still answers with a page reload. For an `update`, Vite has already dropped its cached transform result for the changed file before plugins run, so the next request for that module gets fresh output even when the plugin returns `[]`. ## Re-sending an edited article For the newsroom's `.md` articles, a page can show new text without re-running any module: 1. guard on the environment, and on `type === 'update'` for `.md` files; 2. call `await read()` rather than reading the file directly, because a change event can fire before the editor finishes writing and a direct read may return empty content; 3. render the article and send it with `this.environment.hot.send({ type: 'custom', event: 'news:article-update', data })`; 4. return `[]`. In the browser, a handler registered with `import.meta.hot.on('news:article-update', …)`, often injected by the same plugin's `transform`, swaps the article in place. Prefix event names with a namespace to avoid collisions with other plugins. To force a reload instead, invalidate each affected module with `this.environment.moduleGraph.invalidateModule(mod, seen, timestamp, true)`, send `{ type: 'full-reload' }` and return `[]`. ## Narrow, take over, or react to new files Taking over is not the only useful answer. Some choices by situation: - **One file, several modules.** If an article is imported both as a module and as raw text, `modules` holds both; returning only the ones whose output really changed keeps the update small. - **A file that feeds generated code.** If `virtual:build-info` or an article index is built from the articles folder, an edit should also refresh it: look the virtual module up in `this.environment.moduleGraph`, add it to the returned list, and Vite updates it through the normal path. - **A new or deleted article.** `type` is `'create'` or `'delete'` for files added to or removed from watched folders, so the plugin can send an event that refreshes the article list, which `handleHotUpdate` never saw. ## `hotUpdate` and `handleHotUpdate` - `hotUpdate` arrived in Vite 6 with the Environment API. It is environment-aware and also fires for created and deleted files. - `handleHotUpdate` is the older hook. It runs once per change with a mixed list of client and SSR modules, and only for updates. It is still documented and not yet deprecated; setting `future.removePluginHookHandleHotUpdate` to `'warn'` reports plugins that still use it. - If one plugin defines both, Vite calls `hotUpdate`. - Both accept the object form with `order: 'pre' | 'post'`, which sorts them across plugins. ## Pitfalls - Forgetting the environment guard and sending client events from the SSR pass as well. - Returning `[]` without sending anything, which leaves open tabs silently showing old content. - Expecting the hook during `vite build`, when no dev server is watching files.
- What is the difference between hotUpdate and handleHotUpdate?`handleHotUpdate` is the older hook: it runs once per change with a mixed client and SSR module list, and only for file updates. `hotUpdate`, added in Vite 6, runs once per environment with that environment's modules and also for created and deleted files. Vite still documents `handleHotUpdate` and has not deprecated it; `future.removePluginHookHandleHotUpdate: 'warn'` flags plugins that use it.
- How would the plugin force a full page reload for a changed article instead?Invalidate each entry in `modules` with `this.environment.moduleGraph.invalidateModule(mod, seen, timestamp, true)`, send `this.environment.hot.send({ type: 'full-reload' })` and return `[]`. Vite then skips its own update for that file, and every connected page reloads.
- hotUpdate runs in the browser when a module is swapped.
- hotUpdate is called once per file change, however many environments exist.
- Returning nothing from hotUpdate cancels the update for that file.
- Reading the changed file with a direct file read inside the hook is always safe.
- handleHotUpdate no longer works, so every plugin must migrate immediately.