Skip to content

Commit

Permalink
feat(client): add WebSocket connections events (#13334)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jun 15, 2023
1 parent 2eca54e commit eb75103
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/guide/api-hmr.md
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions packages/vite/src/client/client.ts
Expand Up @@ -81,6 +81,7 @@ function setupWebSocket(
'open',
() => {
isOpened = true
notifyListeners('vite:ws:connect', { webSocket: socket })
},
{ once: true },
)
Expand All @@ -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()
Expand Down
12 changes: 12 additions & 0 deletions packages/vite/types/customEvent.d.ts
Expand Up @@ -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 {
Expand Down

0 comments on commit eb75103

Please sign in to comment.