Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(client): add WebSocket connections events #13334

Merged
merged 2 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/api-hmr.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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