-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
88 lines (70 loc) · 2.4 KB
/
plugin.js
File metadata and controls
88 lines (70 loc) · 2.4 KB
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
79
80
81
82
83
84
85
86
87
88
import { createRequire } from 'node:module';
import WebSocket, { WebSocketServer } from 'ws';
const require = createRequire(import.meta.url);
export class TinyBrowserHmrWebpackPlugin {
hostname;
port;
/**
* @param {Object} options
* @param {string} [options.hostname]
* @param {number} [options.port=8000]
*/
constructor({ hostname, port = 8000 } = {}) {
this.hostname = hostname;
this.port = port;
}
/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
compiler.hooks.entryOption.tap(this.constructor.name, (context, entry) => {
let foundClientEntry = false;
if (typeof entry === 'function') {
throw new Error('Entry cannot be a function');
}
Object.values(entry).forEach(entryValue => {
if (!entryValue.import) return;
const clientIndex = entryValue.import.findIndex(resourcePath => {
try {
const pathname = resourcePath.split('?')[0];
const absPath = require.resolve(pathname, { paths: [context] });
return (
absPath ===
require.resolve('@faergeek/tiny-browser-hmr-webpack-plugin/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', String(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',
);
}
});
/** @type {string | undefined} */
let latestHash;
const wss = new WebSocketServer({ port: this.port });
/** @param {WebSocket} client */
function sendCheck(client) {
if (latestHash) client.send(latestHash);
}
wss.on('connection', sendCheck);
compiler.hooks.done.tap(this.constructor.name, stats => {
latestHash = stats.hash;
Array.from(wss.clients)
.filter(client => client.readyState === WebSocket.OPEN)
.forEach(sendCheck);
});
}
}