Skip to content

Commit aa853a8

Browse files
committed
fix: use import.meta.hot.on to do client server communication
1 parent 7b54a0c commit aa853a8

File tree

5 files changed

+32
-78
lines changed

5 files changed

+32
-78
lines changed

packages/runtime/src/ws.js

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,3 @@
1-
// #region
2-
// copied from https://github.com/vitejs/vite/blob/d76db0cae645beaecd970d95b4819158c5dd568a/packages/vite/src/client/client.ts#LL25
3-
// use server configuration, then fallback to inference
4-
const importMetaUrl = new URL(import.meta.url)
5-
6-
const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')
7-
const hmrPort = __HMR_PORT__
8-
const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${
9-
hmrPort || importMetaUrl.port
10-
}${__HMR_BASE__}`
11-
const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')
12-
// #endregion
13-
141
// #region
152
// NOTE: sync modification with packages/vite-plugin-checker/client/index.ts
163
const WS_CHECKER_ERROR_EVENT = 'vite-plugin-checker:error'
@@ -34,28 +21,24 @@ export function listenToReconnectMessage(cb) {
3421
}
3522

3623
export function prepareListen() {
37-
const onMessage = async ({ data: dataStr }) => {
38-
const data = JSON.parse(dataStr)
39-
switch (data.type) {
40-
case 'update':
24+
const onMessage = async (data) => {
25+
switch (data.event) {
26+
case WS_CHECKER_ERROR_EVENT:
27+
onCustomMessage.forEach((callbackfn) => callbackfn(data.data))
4128
break
42-
case 'full-reload':
29+
case WS_CHECKER_RECONNECT_EVENT:
30+
onReconnectMessage.forEach((callbackfn) => callbackfn(data.data))
4331
break
4432
}
45-
46-
if (data.type === 'custom') {
47-
switch (data.event) {
48-
case WS_CHECKER_ERROR_EVENT:
49-
onCustomMessage.forEach((callbackfn) => callbackfn(data.data))
50-
break
51-
case WS_CHECKER_RECONNECT_EVENT:
52-
onReconnectMessage.forEach((callbackfn) => callbackfn(data.data))
53-
break
54-
}
55-
}
5633
}
5734

5835
return {
59-
start: () => socket.addEventListener('message', onMessage),
36+
start: () => {
37+
if (import.meta.hot) {
38+
import.meta.hot.on('vite-plugin-checker', (data) => {
39+
onMessage(data)
40+
})
41+
}
42+
},
6043
}
6144
}

packages/vite-plugin-checker/src/main.ts

Lines changed: 9 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import chalk from 'chalk'
22
import { spawn } from 'child_process'
33
import pick from 'lodash.pick'
44
import npmRunPath from 'npm-run-path'
5-
import path from 'path'
65
import type { ConfigEnv, Plugin, ResolvedConfig } from 'vite'
76
import { Checker } from './Checker.js'
87
import {
@@ -59,6 +58,7 @@ export function checker(userConfig: UserPluginConfig): Plugin {
5958
let checkers: ServeAndBuildChecker[] = []
6059
let isProduction = true
6160
let skipRuntime = false
61+
let devBase = '/'
6262

6363
let viteMode: ConfigEnv['command'] | undefined
6464
let resolvedConfig: ResolvedConfig | undefined
@@ -87,6 +87,7 @@ export function checker(userConfig: UserPluginConfig): Plugin {
8787
},
8888
configResolved(config) {
8989
resolvedConfig = config
90+
devBase = config.base
9091
isProduction = config.isProduction
9192
skipRuntime ||= isProduction || config.command === 'build'
9293
},
@@ -107,37 +108,11 @@ export function checker(userConfig: UserPluginConfig): Plugin {
107108
},
108109
load(id) {
109110
if (id === RUNTIME_CLIENT_RUNTIME_PATH) {
110-
if (!resolvedConfig) return
111-
112-
const devBase = resolvedConfig.base
113-
114-
// #region
115-
// copied from https://github.com/vitejs/vite/blob/d76db0cae645beaecd970d95b4819158c5dd568a/packages/vite/src/client/client.ts#LL25
116-
const hmrConfig = isObject(resolvedConfig.server.hmr) ? resolvedConfig.server.hmr : {}
117-
const host = hmrConfig.host || null
118-
const protocol = hmrConfig.protocol || null
119-
// hmr.clientPort -> hmr.port
120-
// -> (24678 if middleware mode) -> new URL(import.meta.url).port
121-
let port = hmrConfig?.clientPort || hmrConfig?.port || null
122-
if (resolvedConfig.server.middlewareMode) {
123-
port ||= 24678
124-
}
125-
126-
let hmrBase = devBase
127-
if (hmrConfig?.path) {
128-
hmrBase = path.posix.join(hmrBase, hmrConfig.path)
129-
}
130-
131111
return runtimeCode
132-
.replace(/__HMR_PROTOCOL__/g, JSON.stringify(protocol))
133-
.replace(/__HMR_HOSTNAME__/g, JSON.stringify(host))
134-
.replace(/__HMR_PORT__/g, JSON.stringify(port))
135-
.replace(/__HMR_BASE__/g, JSON.stringify(hmrBase))
136-
// #endregion
137112
}
138113

139114
if (id === RUNTIME_CLIENT_ENTRY_PATH) {
140-
return composePreambleCode(resolvedConfig!.base, overlayConfig)
115+
return composePreambleCode(devBase, overlayConfig)
141116
}
142117

143118
return
@@ -179,7 +154,6 @@ export function checker(userConfig: UserPluginConfig): Plugin {
179154
})()
180155
},
181156
configureServer(server) {
182-
let connectedTimes = 0
183157
let latestOverlayErrors: OverlayErrorAction['payload'][] = new Array(checkers.length)
184158
// for dev mode (2/2)
185159
// Get the server instance and keep reference in a closure
@@ -190,7 +164,7 @@ export function checker(userConfig: UserPluginConfig): Plugin {
190164
if (action.type === ACTION_TYPES.overlayError) {
191165
latestOverlayErrors[index] = action.payload
192166
if (action.payload) {
193-
server.ws.send(action.payload)
167+
server.ws.send('vite-plugin-checker', action.payload)
194168
}
195169
} else if (action.type === ACTION_TYPES.console) {
196170
Checker.log(action)
@@ -204,15 +178,11 @@ export function checker(userConfig: UserPluginConfig): Plugin {
204178
// may update the overlay before full-reload fired. So we make sure the overlay
205179
// will be displayed again after full-reload.
206180
server.ws.on('connection', () => {
207-
connectedTimes++
208-
// if connectedCount !== 1, means Vite is doing a full-reload, so we don't need to send overlay again
209-
if (connectedTimes > 1) {
210-
server.ws.send({
211-
type: 'custom',
212-
event: WS_CHECKER_RECONNECT_EVENT,
213-
data: latestOverlayErrors.filter(Boolean),
214-
})
215-
}
181+
server.ws.send('vite-plugin-checker', {
182+
type: 'custom',
183+
event: WS_CHECKER_RECONNECT_EVENT,
184+
data: latestOverlayErrors.filter(Boolean),
185+
})
216186
})
217187
} else {
218188
setTimeout(() => {
@@ -266,8 +236,4 @@ function spawnChecker(
266236
})
267237
}
268238

269-
function isObject(value: unknown): value is Record<string, any> {
270-
return Object.prototype.toString.call(value) === '[object Object]'
271-
}
272-
273239
export default checker

playground/config-default/vite.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import checker from 'vite-plugin-checker'
33

44
// https://vitejs.dev/config/
55
export default defineConfig({
6+
base: '/my-app/',
67
// config-edit-slot
78
plugins: [
89
checker({

playground/vitestSetup.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,12 +186,16 @@ export async function startDefaultServe(_server?: ViteDevServer, port?: number):
186186
}`
187187

188188
const rawWsSend = server.ws.send
189-
server.ws.send = (_payload) => {
190-
if (_payload.type === 'custom' && _payload.event === 'vite-plugin-checker:error') {
191-
diagnostics = _payload.data.diagnostics
189+
server.ws.send = (...args) => {
190+
const type = args?.[0]
191+
const payload = args?.[1]
192+
193+
if (type === 'vite-plugin-checker' && payload.event === 'vite-plugin-checker:error') {
194+
diagnostics = payload.data.diagnostics
192195
}
193196

194-
return rawWsSend(_payload)
197+
// @ts-ignore
198+
return rawWsSend(...args)
195199
}
196200

197201
await page.goto(viteTestUrl)

vitest.config.e2e.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export default defineConfig({
1414
hookTimeout: timeout,
1515
globals: true,
1616
reporters: 'dot',
17-
outputTruncateLength: 999999999,
17+
outputTruncateLength: Infinity,
1818
onConsoleLog(log) {
1919
if (log.match(/experimental|jit engine|emitted file|tailwind/i)) return false
2020
},

0 commit comments

Comments
 (0)