-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.js
78 lines (60 loc) · 2.02 KB
/
plugin.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
import { createRequire } from 'node:module';
import WebSocket, { WebSocketServer } from 'ws';
const require = createRequire(import.meta.url);
export class TinyBrowserHmrWebpackPlugin {
constructor({ hostname, port = 8000 } = {}) {
this.hostname = hostname;
this.port = port;
}
apply(compiler) {
compiler.hooks.entryOption.tap(this.constructor.name, (context, entry) => {
let foundClientEntry = false;
Object.values(entry).forEach(entryValue => {
const clientIndex = entryValue.import.findIndex(resourcePath => {
try {
const pathname = resourcePath.split('?')[0];
const absPath = require.resolve(pathname, { paths: [context] });
return absPath === require.resolve('./client');
} catch {
return false;
}
});
if (clientIndex !== -1) {
foundClientEntry = true;
const entryPath = entryValue.import[clientIndex];
const [pathname, search] = entryPath.split('?');
const searchParams = new URLSearchParams(search);
if (this.hostname) {
searchParams.set('hostname', this.hostname);
}
searchParams.set('port', this.port);
entryValue.import[clientIndex] = `${pathname}?${searchParams}`;
}
});
if (!foundClientEntry) {
throw new Error(
'TinyBrowserHmrWebpackPlugin is used without adding an entry. Either remove a plugin or add an entry',
);
}
});
let latestHash;
const wss = new WebSocketServer({ port: this.port });
function sendCheck(client) {
if (!latestHash) {
return;
}
client.send(JSON.stringify({ hash: latestHash }));
}
wss.on('connection', client => {
sendCheck(client);
});
compiler.hooks.done.tap(this.constructor.name, stats => {
latestHash = stats.hash;
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
sendCheck(client);
}
});
});
}
}