Skip to content

Commit 4bc9284

Browse files
fix(hmr): catch thrown errors when connecting to hmr websocket (#7111)
Co-authored-by: patak-dev <matias.capeletto@gmail.com>
1 parent c86329b commit 4bc9284

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

packages/vite/src/client/client.ts

+20-14
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,29 @@ console.log('[vite] connecting...')
1919
const socketProtocol =
2020
__HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')
2121
const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`
22-
const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')
2322
const base = __BASE__ || '/'
2423
const messageBuffer: string[] = []
2524

25+
let socket: WebSocket
26+
try {
27+
socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')
28+
29+
// Listen for messages
30+
socket.addEventListener('message', async ({ data }) => {
31+
handleMessage(JSON.parse(data))
32+
})
33+
34+
// ping server
35+
socket.addEventListener('close', async ({ wasClean }) => {
36+
if (wasClean) return
37+
console.log(`[vite] server connection lost. polling for restart...`)
38+
await waitForSuccessfulPing()
39+
location.reload()
40+
})
41+
} catch (error) {
42+
console.error(`[vite] failed to connect to websocket (${error}). `)
43+
}
44+
2645
function warnFailedFetch(err: Error, path: string | string[]) {
2746
if (!err.message.match('fetch')) {
2847
console.error(err)
@@ -40,11 +59,6 @@ function cleanUrl(pathname: string): string {
4059
return url.pathname + url.search
4160
}
4261

43-
// Listen for messages
44-
socket.addEventListener('message', async ({ data }) => {
45-
handleMessage(JSON.parse(data))
46-
})
47-
4862
let isFirstUpdate = true
4963

5064
async function handleMessage(payload: HMRPayload) {
@@ -212,14 +226,6 @@ async function waitForSuccessfulPing(ms = 1000) {
212226
}
213227
}
214228

215-
// ping server
216-
socket.addEventListener('close', async ({ wasClean }) => {
217-
if (wasClean) return
218-
console.log(`[vite] server connection lost. polling for restart...`)
219-
await waitForSuccessfulPing()
220-
location.reload()
221-
})
222-
223229
// https://wicg.github.io/construct-stylesheets
224230
const supportsConstructedSheet = (() => {
225231
// TODO: re-enable this try block once Chrome fixes the performance of

0 commit comments

Comments
 (0)