diff --git a/docs/guide/api-hmr.md b/docs/guide/api-hmr.md index 13f76239892331..0704b0cc1cfa71 100644 --- a/docs/guide/api-hmr.md +++ b/docs/guide/api-hmr.md @@ -29,6 +29,7 @@ interface ViteHotContext { ): void dispose(cb: (data: any) => void): void + prune(cb: (data: any) => void): void decline(): void invalidate(message?: string): void @@ -115,6 +116,18 @@ if (import.meta.hot) { } ``` +## `hot.prune(cb)` + +Register a callback that will call when the module is no longer imported on the page. This can be used to clean up side effects like style injections. Vite already does this for `.css` imports. + +```js +if (import.meta.hot) { + import.meta.hot.prune((data) => { + // cleanup side effect + }) +} +``` + ## `hot.data` The `import.meta.hot.data` object is persisted across different instances of the same updated module. It can be used to pass on information from a previous version of the module to the next one. diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 12e2a95b383ff1..bfa0c44231cada 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -548,8 +548,7 @@ export function createHotContext(ownerPath: string): ViteHotContext { disposeMap.set(ownerPath, cb) }, - // @ts-expect-error untyped - prune(cb: (data: any) => void) { + prune(cb) { pruneMap.set(ownerPath, cb) }, diff --git a/packages/vite/types/hot.d.ts b/packages/vite/types/hot.d.ts index d51bb6e6156e1c..1a67a9087a6e68 100644 --- a/packages/vite/types/hot.d.ts +++ b/packages/vite/types/hot.d.ts @@ -22,6 +22,7 @@ export interface ViteHotContext { ): void dispose(cb: (data: any) => void): void + prune(cb: (data: any) => void): void decline(): void invalidate(message?: string): void