-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmr.jsx
58 lines (54 loc) · 1.2 KB
/
hmr.jsx
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
export function LiveReloadScript() {
return (
<script
dangerouslySetInnerHTML={{
__html: `
const source = new EventSource('/hmr');
source.onopen = () => {
console.log('HMR connected');
};
source.onmessage = (event) => {
if (event.data === 'hmr') {
console.log('HMR reloading');
location.reload();
}
}`,
}}
/>
);
}
export function hmrMiddleware() {
return () => {
/**
* @type {EventListener}
*/
let eventListener;
/**
* @param {string} data
* @returns
*/
function encode(data) {
return new TextEncoder().encode(data);
}
const body = new ReadableStream({
start(controller) {
addEventListener(
'hmr',
(eventListener = () => {
controller.enqueue(encode('data: hmr\n\n'));
})
);
},
cancel() {
removeEventListener('hmr', eventListener);
},
});
return new Response(body, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
};
}