Skip to content

Commit eb75103

Browse files
authoredJun 15, 2023
feat(client): add WebSocket connections events (#13334)
1 parent 2eca54e commit eb75103

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed
 

‎docs/guide/api-hmr.md

+2
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,8 @@ The following HMR events are dispatched by Vite automatically:
176176
- `'vite:beforePrune'` when modules that are no longer needed are about to be pruned
177177
- `'vite:invalidate'` when a module is invalidated with `import.meta.hot.invalidate()`
178178
- `'vite:error'` when an error occurs (e.g. syntax error)
179+
- `'vite:ws:disconnect'` when the WebSocket connection is lost
180+
- `'vite:ws:connect'` when the WebSocket connection is (re-)established
179181
180182
Custom HMR events can also be sent from plugins. See [handleHotUpdate](./api-plugin#handlehotupdate) for more details.
181183

‎packages/vite/src/client/client.ts

+3
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ function setupWebSocket(
8181
'open',
8282
() => {
8383
isOpened = true
84+
notifyListeners('vite:ws:connect', { webSocket: socket })
8485
},
8586
{ once: true },
8687
)
@@ -99,6 +100,8 @@ function setupWebSocket(
99100
return
100101
}
101102

103+
notifyListeners('vite:ws:disconnect', { webSocket: socket })
104+
102105
console.log(`[vite] server connection lost. polling for restart...`)
103106
await waitForSuccessfulPing(protocol, hostAndPath)
104107
location.reload()

‎packages/vite/types/customEvent.d.ts

+12
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@ export interface CustomEventMap {
1212
'vite:beforeFullReload': FullReloadPayload
1313
'vite:error': ErrorPayload
1414
'vite:invalidate': InvalidatePayload
15+
'vite:ws:connect': WebSocketConnectionPayload
16+
'vite:ws:disconnect': WebSocketConnectionPayload
17+
}
18+
19+
export interface WebSocketConnectionPayload {
20+
/**
21+
* @experimental
22+
* We expose this instance experimentally to see potential usage.
23+
* This might be removed in the future if we didn't find reasonable use cases.
24+
* If you find this useful, please open an issue with details so we can discuss and make it stable API.
25+
*/
26+
webSocket: WebSocket
1527
}
1628

1729
export interface InvalidatePayload {

0 commit comments

Comments
 (0)
Please sign in to comment.