diff --git a/apps/electron/main/index.ts b/apps/electron/main/index.ts index 9ad10f4f..7ed7ba30 100644 --- a/apps/electron/main/index.ts +++ b/apps/electron/main/index.ts @@ -3,6 +3,7 @@ import { app, ipcMain, shell, type IpcMain } from "electron"; import "./security-restrictions"; import type cp from "child_process"; import { callProcedure } from "@trpc/server"; +import ip from "ip"; import { appRouter, createContext } from "@acme/api"; import { closeAssetsServer } from "@acme/assets-server"; @@ -57,6 +58,17 @@ app.on("quit", () => { nextjsWebChild?.kill(); }); +app.on("browser-window-focus", () => { + void (async () => { + // 如果 ip 不相同,并且已经启动才需要重启 + // web server 首次启动在 activate 中触发 + console.log(process.env["IP"], ip.address()); + if (nextjsWebChild && process.env["IP"] != ip.address()) { + nextjsWebChild = await createWebServer(nextjsWebChild); + } + })(); +}); + /** * @see https://www.electronjs.org/docs/latest/api/app#event-activate-macos Event: 'activate'. */ diff --git a/apps/electron/main/src/createWebServer.ts b/apps/electron/main/src/createWebServer.ts index c370fbc5..5c7b1c67 100644 --- a/apps/electron/main/src/createWebServer.ts +++ b/apps/electron/main/src/createWebServer.ts @@ -19,11 +19,12 @@ export const createWebServer = async (preNextChild?: cp.ChildProcess) => { const _assets_port = isPackaged ? (await getPort({ portRange: [9625, 9629], port: 9625 })).toString() : "9625"; // Init env variables - process.env["IP"] = _ip; process.env["WEB_PORT"] = _web_port; process.env["ASSETS_PORT"] = _assets_port; if (isPackaged) { + process.env["IP"] = _ip; + preNextChild?.kill(); // app config production // dev 在 watchDesktop.ts 中指定 @@ -41,7 +42,10 @@ export const createWebServer = async (preNextChild?: cp.ChildProcess) => { }); } else { // 开发环境 next dev 会自动进行热更新,不需要 kill - if (preNextChild) return; + if (preNextChild && _ip === process.env["IP"]) return; + process.env["IP"] = _ip; + + preNextChild?.kill(); const nextjs = join(process.cwd(), "../nextjs"); nextjsChild = cp.spawn("npx", ["next", "dev"], { shell: true,