【问题标题】:execute child_process in a electron + react application在电子 + 反应应用程序中执行 child_process
【发布时间】:2020-08-10 07:13:23
【问题描述】:

我开始使用 reactjs 创建一个电子应用程序。我正在使用 react-react-app 方法来创建反应应用程序。在我的应用程序中,我想执行一些 cli 命令。每次我使用“child_process”时都会出错。有时会说“child_process.exec 不是函数”。那么如何在这个项目中执行/使用“child_process”方法/函数。非常感谢

cli.js

export const cli = () => {
 try {
  const { spawn } = require('child_process');
  const ls = spawn('ls', ['-lh', '/usr']);

  ls.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });

  ls.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
  });

  ls.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
 } catch(error) {
  console.log(error)
 }

}

app.js

import { cli } from "./cli";

function App() {

// call cli function
cli();

return (
<div className="App">
  <header className="App-header">
    <img src={logo} className="App-logo" alt="logo" />
    <p>
      Edit <code>src/App.js</code> and save to reload.
    </p>
    <a
      className="App-link"
      href="https://reactjs.org"
      target="_blank"
      rel="noopener noreferrer"
    >
      Learn React
    </a>
  </header>
</div>
);

}

【问题讨论】:

  • 你可以添加更多信息,错误给你的问题
  • 在创建browserWindow 时启用nodeintegration 标志。
  • 我建议您在主进程中运行子进程,而不是在渲染器中。
  • @tpikachu 哇,你给了我很多问题的答案。谢谢

标签: node.js reactjs electron command-line-interface child-process


【解决方案1】:

您需要添加 webpack 目标和广告 webPreferences,如下所示。 在我的项目中,我更新了以下文件以使其正常工作。

webpack.main.config.js

module.exports = {
  // Your other configs
  target: 'electron-main'
};

webpack.renderer.config.js

module.exports = {
  // Your other configs
  target: 'electron-renderer'
};

index.js 或 index.ts

const mainWindow = new BrowserWindow({
  // Your other configs
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false
  }
});

然后你可以在你的代码中使用 child_process

import { spawn } from 'child_process';
// Your code with spawn

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2021-01-06
    • 2018-12-27
    • 2021-11-11
    • 2017-10-14
    • 2021-05-17
    • 2018-12-15
    相关资源
    最近更新 更多