diff --git a/docs/guide/api-hmr.md b/docs/guide/api-hmr.md index 499838a0faa47f..8bbb5b0df9fbc1 100644 --- a/docs/guide/api-hmr.md +++ b/docs/guide/api-hmr.md @@ -176,6 +176,8 @@ The following HMR events are dispatched by Vite automatically: - `'vite:beforePrune'` when modules that are no longer needed are about to be pruned - `'vite:invalidate'` when a module is invalidated with `import.meta.hot.invalidate()` - `'vite:error'` when an error occurs (e.g. syntax error) +- `'vite:ws:disconnect'` when the WebSocket connection is lost +- `'vite:ws:connect'` when the WebSocket connection is (re-)established Custom HMR events can also be sent from plugins. See [handleHotUpdate](./api-plugin#handlehotupdate) for more details. diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 0abf5bccef0944..cc09f8b8f175db 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -81,6 +81,7 @@ function setupWebSocket( 'open', () => { isOpened = true + notifyListeners('vite:ws:connect', { webSocket: socket }) }, { once: true }, ) @@ -99,6 +100,8 @@ function setupWebSocket( return } + notifyListeners('vite:ws:disconnect', { webSocket: socket }) + console.log(`[vite] server connection lost. polling for restart...`) await waitForSuccessfulPing(protocol, hostAndPath) location.reload() diff --git a/packages/vite/types/customEvent.d.ts b/packages/vite/types/customEvent.d.ts index c27bde437e97bf..a72c1b85fc1ad0 100644 --- a/packages/vite/types/customEvent.d.ts +++ b/packages/vite/types/customEvent.d.ts @@ -12,6 +12,18 @@ export interface CustomEventMap { 'vite:beforeFullReload': FullReloadPayload 'vite:error': ErrorPayload 'vite:invalidate': InvalidatePayload + 'vite:ws:connect': WebSocketConnectionPayload + 'vite:ws:disconnect': WebSocketConnectionPayload +} + +export interface WebSocketConnectionPayload { + /** + * @experimental + * We expose this instance experimentally to see potential usage. + * This might be removed in the future if we didn't find reasonable use cases. + * If you find this useful, please open an issue with details so we can discuss and make it stable API. + */ + webSocket: WebSocket } export interface InvalidatePayload {