Skip to content

Commit

Permalink
fix(hmr): catch thrown errors when connecting to hmr websocket (#7111)
Browse files Browse the repository at this point in the history
Co-authored-by: patak-dev <matias.capeletto@gmail.com>
  • Loading branch information
JadedBlueEyes and patak-dev committed May 18, 2022
1 parent c86329b commit 4bc9284
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions packages/vite/src/client/client.ts
Expand Up @@ -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)
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 4bc9284

Please sign in to comment.