From 4bc92843ffad2cc076813e74bde215ebc7443d87 Mon Sep 17 00:00:00 2001 From: Joel Ellis Date: Wed, 18 May 2022 19:18:24 +0100 Subject: [PATCH] fix(hmr): catch thrown errors when connecting to hmr websocket (#7111) Co-authored-by: patak-dev --- packages/vite/src/client/client.ts | 34 ++++++++++++++++++------------ 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 6a7f9b27c3a700..1a1968168683c1 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -19,10 +19,29 @@ console.log('[vite] connecting...') const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws') const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}` -const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr') const base = __BASE__ || '/' const messageBuffer: string[] = [] +let socket: WebSocket +try { + socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr') + + // Listen for messages + socket.addEventListener('message', async ({ data }) => { + handleMessage(JSON.parse(data)) + }) + + // ping server + socket.addEventListener('close', async ({ wasClean }) => { + if (wasClean) return + console.log(`[vite] server connection lost. polling for restart...`) + await waitForSuccessfulPing() + location.reload() + }) +} catch (error) { + console.error(`[vite] failed to connect to websocket (${error}). `) +} + function warnFailedFetch(err: Error, path: string | string[]) { if (!err.message.match('fetch')) { console.error(err) @@ -40,11 +59,6 @@ function cleanUrl(pathname: string): string { return url.pathname + url.search } -// Listen for messages -socket.addEventListener('message', async ({ data }) => { - handleMessage(JSON.parse(data)) -}) - let isFirstUpdate = true async function handleMessage(payload: HMRPayload) { @@ -212,14 +226,6 @@ async function waitForSuccessfulPing(ms = 1000) { } } -// ping server -socket.addEventListener('close', async ({ wasClean }) => { - if (wasClean) return - console.log(`[vite] server connection lost. polling for restart...`) - await waitForSuccessfulPing() - location.reload() -}) - // https://wicg.github.io/construct-stylesheets const supportsConstructedSheet = (() => { // TODO: re-enable this try block once Chrome fixes the performance of