From 18b9b31d79d2a05e10b519a9f112fe857c1b7202 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Wed, 21 Feb 2024 15:20:29 +0800 Subject: [PATCH] docs(hmr): improve handleHotUpdate and add further reading (#15996) --- docs/guide/api-hmr.md | 6 ++++++ docs/guide/api-plugin.md | 24 +++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/guide/api-hmr.md b/docs/guide/api-hmr.md index e55f0af47090e0..a24fe277fbfe24 100644 --- a/docs/guide/api-hmr.md +++ b/docs/guide/api-hmr.md @@ -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) diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index 40b8261d88e740..eb62b70cc809d8 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -402,6 +402,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo ### `handleHotUpdate` - **Type:** `(ctx: HmrContext) => Array | void | Promise | void>` +- **See also:** [HMR API](./api-hmr) Perform custom HMR update handling. The hook receives a context object with the following signature: @@ -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',