-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
78 lines (63 loc) · 1.75 KB
/
client.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* eslint-env browser */
/* globals __resourceQuery, __webpack_hash__ */
if (!import.meta.webpackHot) {
throw new Error(
'TinyBrowserHmrWebpackPlugin client entry is used without HotModuleReplacementPlugin. Either remove an entry or add a plugin',
);
}
const searchParams = new URLSearchParams(__resourceQuery);
const hostname = searchParams.get('hostname');
const port = searchParams.get('port');
if (!port) {
throw new Error(
'TinyBrowserHmrWebpackPlugin client entry is used without TinyBrowserHmrWebpackPlugin. Either remove an entry or add a plugin',
);
}
connect();
function connect() {
const ws = new WebSocket(`ws://${hostname || location.hostname}:${port}`);
ws.onmessage = async event => {
const { hash } = JSON.parse(event.data);
checkForUpdates(hash);
};
ws.onclose = () => {
setTimeout(() => {
connect();
}, 5000);
};
}
function waitForIdle() {
if (import.meta.webpackHot.status() === 'idle') {
return;
}
return new Promise((resolve, reject) => {
function statusHandler(status) {
switch (status) {
case 'idle':
resolve();
break;
case 'abort':
case 'fail':
reject(new Error(`HMR status: "${status}"`));
break;
default:
return;
}
import.meta.webpackHot.removeStatusHandler(statusHandler);
}
import.meta.webpackHot.addStatusHandler(statusHandler);
});
}
async function checkForUpdates(hash) {
if (hash === __webpack_hash__) {
return;
}
await waitForIdle();
const updatedModules = await import.meta.webpackHot.check(true);
if (!updatedModules) {
throw new Error(
'Could not find an update, probably because of the server restart',
);
}
checkForUpdates(hash);
}