Skip to content

Commit

Permalink
docs(hmr): improve handleHotUpdate and add further reading (#15996)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Feb 21, 2024
1 parent f3b195c commit 18b9b31
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 6 additions & 0 deletions docs/guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,9 @@ Send custom events back to Vite's dev server.
If called before connected, the data will be buffered and sent once the connection is established.
See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details.
## Further Reading
If you'd like to learn more about how to use the HMR API and how it works under-the-hood. Check out these resources:
- [Hot Module Replacement is Easy](https://bjornlu.com/blog/hot-module-replacement-is-easy)
24 changes: 23 additions & 1 deletion docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
### `handleHotUpdate`

- **Type:** `(ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>`
- **See also:** [HMR API](./api-hmr)

Perform custom HMR update handling. The hook receives a context object with the following signature:

Expand All @@ -423,10 +424,31 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
- Filter and narrow down the affected module list so that the HMR is more accurate.
- Return an empty array and perform complete custom HMR handling by sending custom events to the client (example uses `server.hot` which was introduced in Vite 5.1, it is recommended to also use `server.ws` if you support lower versions):
- Return an empty array and perform a full reload:
```js
handleHotUpdate({ server, modules, timestamp }) {
// Also use `server.ws.send` to support Vite <5.1 if needed
server.hot.send({ type: 'full-reload' })
// Invalidate modules manually
const invalidatedModules = new Set()
for (const mod of modules) {
server.moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true
)
}
return []
}
```
- Return an empty array and perform complete custom HMR handling by sending custom events to the client:
```js
handleHotUpdate({ server }) {
// Also use `server.ws.send` to support Vite <5.1 if needed
server.hot.send({
type: 'custom',
event: 'special-update',
Expand Down

0 comments on commit 18b9b31

Please sign in to comment.