首页 > 解决方案 > 无法在电子应用程序中使用 child_process - 反应 ui,环境 WSL

问题描述

我正在使用带有 React UI 的 Electron 开发一个桌面应用程序,我的开发环境是 WSL2。

编辑:我尝试从 powershell 运行应用程序并遇到了同样的问题,所以我确定这不是 WSL 问题。

主.js

const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");
const dotenv = require("dotenv");
dotenv.config();
let devtools = null;

let mainWindow;
function createWindow() {
  const startUrl =
    process.env.ELECTRON_START_URL ||
    url.format({
      pathname: path.join(__dirname, "../index.html"),
      devTools: true,
      protocol: "file:",
      slashes: true,
    });

  mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    },
    width: 800,
    height: 600,
  });

  devtools = new BrowserWindow({ width: 800, height: 600 });
  mainWindow.webContents.setDevToolsWebContents(devtools.webContents);
  mainWindow.webContents.openDevTools({ mode: "detach" });

  mainWindow.loadURL(startUrl);

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

这是我的 ui 组件:

import React from "react";

import { Button } from "@ui5/webcomponents-react/lib/Button";
import "@ui5/webcomponents-icons/dist/begin";

import "./TestLaunchButton.css";
import { exec } from "child_process";

export const buttonText = "Launch Test";

function TestLaunchButton({ batFileName }) {
  const handleClick = (event) => {
    const batFileName = event.target.dataset.batfile;
    const options = { shell: "cmd.exe" };
    exec("dir", options, (error, stdout, stderr) => {
      if (error) {
        console.log(`error: ${error.message}`);
        return;
      }
      if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
    });

    return (
      <div className="launch-button">
        <Button onClick={handleClick} data-batfile={batFileName} icon="begin" />
      </div>
    );
  };
}
export default TestLaunchButton;

但是,当我尝试执行子进程时,我导入的任何内容都会显示为“未定义”,从而使我的代码引发以下错误:

在此处输入图像描述

谁能解释如何访问child_process?

我已经看到很多帖子说“只需在 webPreferences 中添加 'nodeIntegration: true'”,但正如您从上面看到的那样,我已经这样做了,结果是一样的。我怀疑这可能与使用 WSL2 有关,但我无法确认。有人知道吗?

标签: node.jsreactjselectronchild-process

解决方案


推荐阅读