-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
emitter.ts
62 lines (55 loc) · 1.72 KB
/
emitter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { EventEmitter } from 'node:events'
import type { HMRPayload, Plugin } from 'vite'
export type EventType = string | symbol
export type Handler<T = unknown> = (event: T) => void
export interface Emitter<Events extends Record<EventType, unknown>> {
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void
}
export type HMREmitter = Emitter<{
'message': HMRPayload
}> & EventEmitter
declare module 'vite' {
interface ViteDevServer {
emitter: HMREmitter
}
}
export function createHmrEmitter(): HMREmitter {
const emitter = new EventEmitter()
return emitter
}
export function viteNodeHmrPlugin(): Plugin {
const emitter = createHmrEmitter()
return {
name: 'vite-node:hmr',
config() {
// chokidar fsevents is unstable on macos when emitting "ready" event
if (process.platform === 'darwin' && process.env.VITE_TEST_WATCHER_DEBUG) {
return {
server: {
watch: {
useFsEvents: false,
usePolling: false,
},
},
}
}
},
configureServer(server) {
const _send = server.ws.send
server.emitter = emitter
server.ws.send = function (payload: any) {
_send(payload)
emitter.emit('message', payload)
}
if (process.env.VITE_TEST_WATCHER_DEBUG) {
server.watcher.on('ready', () => {
// eslint-disable-next-line no-console
console.log('[debug] watcher is ready')
})
}
},
}
}