vite-dev.mjs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { spawn } from "node:child_process";
  2. import { fileURLToPath } from "node:url";
  3. import { setTimeout as sleep } from "node:timers/promises";
  4. const workspaceRoot = fileURLToPath(new URL("../", import.meta.url));
  5. // 当前 Vite dev server 只监听 localhost,不接受 127.0.0.1。
  6. // 之前这里一直轮询 127.0.0.1,会导致 preLaunchTask 永远不 ready,后续 Electron 启动任务完全不执行。
  7. const viteUrl = "http://localhost:5174";
  8. let child;
  9. async function isViteReady() {
  10. try {
  11. const response = await fetch(viteUrl);
  12. return response.ok;
  13. } catch {
  14. return false;
  15. }
  16. }
  17. async function waitForServer() {
  18. while (true) {
  19. if (await isViteReady()) {
  20. break;
  21. }
  22. if (child?.exitCode != null) {
  23. process.exit(child.exitCode);
  24. }
  25. await sleep(300);
  26. }
  27. }
  28. child = spawn(
  29. process.platform === "win32" ? "pnpm.cmd" : "pnpm",
  30. ["--filter", "@zcode/desktop", "exec", "vite", "dev"],
  31. {
  32. cwd: workspaceRoot,
  33. stdio: "inherit",
  34. },
  35. );
  36. void waitForServer();
  37. for (const signal of ["SIGINT", "SIGTERM"]) {
  38. process.on(signal, () => {
  39. if (child != null && !child.killed) {
  40. child.kill(signal);
  41. return;
  42. }
  43. process.exit(0);
  44. });
  45. }
  46. if (child != null) {
  47. child.on("exit", (code, signal) => {
  48. if (signal != null) {
  49. process.kill(process.pid, signal);
  50. return;
  51. }
  52. process.exit(code ?? 0);
  53. });
  54. }