build: Extract watcher

This commit is contained in:
Remko Tronçon 2022-11-20 08:47:27 +01:00
parent c00ae873e9
commit 3494e15a65
2 changed files with 46 additions and 37 deletions

View file

@ -6,45 +6,9 @@ const esbuild = require("esbuild");
const path = require("path");
const fs = require("fs");
const { createServer } = require("http");
const { withWatcher } = require("./scripts/esbuild/watcher");
const { wasmTextPlugin } = require("./scripts/esbuild/wasm-text");
function withWatcher(
config,
handleBuildFinished = () => {
/* do nothing */
},
port = 8880
) {
const watchClients = [];
createServer((req, res) => {
return watchClients.push(
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Access-Control-Allow-Origin": "*",
Connection: "keep-alive",
})
);
}).listen(port);
return {
...config,
banner: {
js: `(function () { new EventSource("http://localhost:${port}").onmessage = function() { location.reload();};})();`,
},
watch: {
async onRebuild(error, result) {
if (error) {
console.error(error);
} else {
await handleBuildFinished(result);
watchClients.forEach((res) => res.write("data: update\n\n"));
watchClients.length = 0;
}
},
},
};
}
let dev = false;
let watch = false;
for (const arg of process.argv.slice(2)) {

View file

@ -0,0 +1,45 @@
/* eslint-env node */
/* eslint @typescript-eslint/no-var-requires:0 */
const { createServer } = require("http");
function withWatcher(
config,
handleBuildFinished = () => {
/* do nothing */
},
port = 8880
) {
const watchClients = [];
createServer((req, res) => {
return watchClients.push(
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Access-Control-Allow-Origin": "*",
Connection: "keep-alive",
})
);
}).listen(port);
return {
...config,
banner: {
js: `(function () { new EventSource("http://localhost:${port}").onmessage = function() { location.reload();};})();`,
},
watch: {
async onRebuild(error, result) {
if (error) {
console.error(error);
} else {
await handleBuildFinished(result);
watchClients.forEach((res) => res.write("data: update\n\n"));
watchClients.length = 0;
}
},
},
};
}
module.exports = {
withWatcher,
};