This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Doric/doric-cli/src/dev.ts

107 lines
2.7 KiB
TypeScript
Raw Normal View History

2021-02-05 18:20:42 +08:00
import { exec } from "child_process"
import chokidar from "chokidar";
2021-02-20 17:58:09 +08:00
import { createServer, MSG } from "./server"
2021-02-05 18:20:42 +08:00
import { delay } from "./util";
import fs from "fs";
import { mergeMap } from "./actions";
import os from "os";
import qrcode from "qrcode-terminal";
import keypress from "keypress";
function getIPAdress() {
const ret: string[] = [];
const interfaces = os.networkInterfaces();
Object.entries(interfaces).map(e => e[1])
.forEach(e => {
if (!!!e) {
return;
}
e.forEach(e => {
if (
e.family === "IPv4" &&
e.address !== "127.0.0.1" &&
!e.internal
) {
ret.push(e.address);
}
})
});
return ret;
}
export default async function dev() {
const server = await createServer()
const tscProcess = exec("node node_modules/.bin/tsc -w -p .");
const rollupProcess = exec("node node_modules/.bin/rollup -c -w");
console.warn("Waiting ...");
const ips = getIPAdress();
ips.forEach((e) => {
console.log(`IP:${e}`);
qrcode.generate(e, { small: true });
});
keypress(process.stdin);
process.stdin.on("keypress", function (ch, key) {
if (key && key.ctrl && key.name == "r") {
ips.forEach((e) => {
console.log(`IP:${e}`);
qrcode.generate(e, { small: true });
});
}
if (key && key.ctrl && key.name == "c") {
process.stdin.pause();
tscProcess.kill("SIGABRT");
rollupProcess.kill("SIGABRT");
process.exit(0);
}
});
process.stdin.setRawMode(true);
process.stdin.resume();
await delay(3000);
console.warn("Start watching");
2021-02-05 19:36:25 +08:00
const cachedContents: Record<string, string> = {}
2021-02-05 18:20:42 +08:00
chokidar
.watch(process.cwd() + "/bundle", {
ignored: /.*?\.map/,
alwaysStat: true,
})
.on("change", (jsFile) => {
2021-02-05 19:36:25 +08:00
const content = fs.readFileSync(jsFile, "utf-8");
if (cachedContents[jsFile]) {
if (content.indexOf(cachedContents[jsFile]) >= 0) {
return;
}
}
cachedContents[jsFile] = content;
2021-02-05 18:20:42 +08:00
console.log("*******", jsFile.replace(process.cwd(), "")
.replace("/bundle/src/", "")
.replace(".js", "")
2021-02-21 01:57:29 +08:00
.green, "*******");
2021-02-05 19:36:25 +08:00
try {
2021-02-07 16:33:31 +08:00
const sourceMap = `${jsFile}.map`
if (fs.existsSync(sourceMap)) {
mergeMap(sourceMap);
}
2021-02-19 17:57:15 +08:00
server.clients.forEach((e) => {
e.send(
2021-02-05 19:36:25 +08:00
JSON.stringify({
2021-02-20 17:58:09 +08:00
type: "S2C",
2021-02-05 19:36:25 +08:00
cmd: "RELOAD",
2021-02-20 17:58:09 +08:00
payload: {
script: content,
source: (jsFile.match(/[^/\\]*$/) || [""])[0],
sourceMap,
}
} as MSG)
2021-02-05 19:36:25 +08:00
);
});
} catch (e) {
console.error(e);
}
2021-02-05 18:20:42 +08:00
});
}