You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Node.js+Electron项目执行npm run electron-start后窗口未弹出

问题原因与解决方案

核心问题1:启动脚本逻辑错误

你的electron-start脚本写法存在逻辑漏洞:

  • concurrently \"npm run start-server\" \"npm run start-client\" && wait-on http://localhost:3000 && electron .中,start-client启动的是React开发服务器,属于长期运行的进程,不会主动退出。
  • &&要求前一个命令执行完成(退出码为0)才会执行后续命令,因此wait-on和electron .永远不会被触发,这是Electron窗口未出现的直接原因。

修复脚本

修改根目录package.json的electron-start脚本,将wait-on与electron的启动逻辑纳入concurrently管理,确保React服务就绪后再启动Electron:

"scripts": {
    "start": "npm run electron-start",
    "start-client": "cd client && BROWSER=none npm start ",
    "start-server": "cd server && node server.js",
    "electron-start": "concurrently \"npm run start-server\" \"npm run start-client\" \"wait-on http://localhost:3000 && electron .\"",
    "build-electron": "electron-builder"
  }

三个命令并行执行,第三个命令会先等待http://localhost:3000就绪,再启动Electron主进程。

核心问题2:Electron主进程代码存在未初始化变量

你的Electron代码中,reactProcess变量仅声明但从未赋值,一旦Electron启动,会触发Cannot read property 'stdout' of undefined报错,导致窗口创建失败。

修复Electron代码

React服务已通过脚本启动,无需在Electron中重复管理,直接删除所有reactProcess相关代码:

const { app, BrowserWindow } = require("electron");
const path = require("path");

let mainWindow;

function createWindow() {
  console.log("Creating Electron window...");
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  // Load the React app
  mainWindow
    .loadURL("http://localhost:3000")
    .then(() => {
      console.log("Loaded React app in Electron window.");
      mainWindow.webContents.on("did-finish-load", () => {
        console.log(`Current URL: ${mainWindow.webContents.getURL()}`);
      });
    })
    .catch((err) => {
      console.error("Failed to load URL in Electron window:", err);
    });

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

app.on("ready", () => {
  console.log("Electron app is ready");
  createWindow();
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
app.on("activate", () => {
  if (mainWindow === null) {
    createWindow();
  }
});

额外优化建议

  • 确保wait-on已安装:若项目未安装,执行npm install wait-on --save-dev。
  • 可给wait-on添加超时参数,比如wait-on http://localhost:3000 -t 30000,避免无限等待。

内容的提问来源于stack exchange,提问作者Matej Hackl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:47:32