node.js - 无法在电子应用程序中使用 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 有关,但我无法确认。有人知道吗?
解决方案
推荐阅读
- android - 为什么 Android Studio 在创建 Fragment 时使用 let 而不是 run
- java - Java Spring Security OAuth2:通过 POST 接受客户端凭据
- javascript - 订阅 - 带有 AWS AppSync 的 Vue-Apollo - 未处理的 GraphQL 订阅错误
- java - CLOSED 将一个单词添加到单词列表中
- javascript - JavaScript:匹配不是函数
- java - 如何在 Spring Boot 应用程序中初始化 AWS SDK?
- java - 永远隐藏导航栏
- ios - iOS 10,swift 4.1,将视图的顶部锚点设置为 topLayoutGuide 底部锚点导致冲突
- asp.net-mvc - 同时添加数百万条记录
- r - R:对特定子集按行分组和求和