[#5675] Reconnect HMR socket without reloading the browser page
Description
Fixes issue #5675 by seamlessly replacing the socket object in the client.js module when the server becomes available again after a socket disconnect.
The socket variable used in the code is already in scope to be replaced, but was being masked by a local socket variable of the same name in the setupWebSocket function. This PR simply renames the local socket variable, allowing the top level socket variable to be assigned the new socket object when reconnection is successful.
HMR works properly now after a socket reconnect without needing to reload the page.
Run & review this pull request in StackBlitz Codeflow.
Is this safe? A file could be edited in between the reconnection, or a different server of a different project could started on the same port, and both cases should trigger a full reload to fetch the new contents?
Maybe I'm missing something. @sapphi-red do you have an idea to support this from the issue? Or is https://github.com/vitejs/vite/issues/5675#issuecomment-1345588419 the fix you're suggesting? (Seems to be about a different issue though I think)
I don't think doing this is safe, too.
My suggestion (https://github.com/vitejs/vite/issues/5675#issuecomment-1345588419) should fix cases like https://github.com/vitejs/vite/issues/10840#issuecomment-1308352901, https://github.com/vitejs/vite/pull/9007#issuecomment-1344261946, https://github.com/vitejs/vite/issues/16536, https://github.com/vitejs/vite/issues/13125. I think I misunderstood the OP (https://github.com/vitejs/vite/issues/5675#issue-1052864790) and thought it's a same thing because it said "Reconnect WebSocket to check HMR status" in the suggested solution.
I'll close this PR as it's unsafe. But feel free to create a new one if you come up with a safe way.