【问题标题】:using electron api from react component使用来自反应组件的电子 API
【发布时间】:2019-01-14 18:16:14
【问题描述】:

我正在使用电子和反应,反应应用程序是使用 create-react-app 样板创建的。我需要使用电子 API 打开一个外部链接,但这个任务是从一个反应组件实现的。我在反应组件中导入了远程电子(为了访问当前窗口。)但这给了我一个错误

const {remote} = require("electron")

错误是由电子本身引发的,来自node_modules/electron/index.js,问题出在 fs 模块上,它说:

TypeError: fs.existsSync is not a function

此错误显示在电子窗口中。

【问题讨论】:

  • github.com/electron/electron/issues/7300 可能是一个类似的问题。解决方案是使用 window.require('electron')
  • 这对我有用。谢谢
  • 没问题。不过,我建议阅读整个线程,因为根据您的构建环境,它可能会对应用程序的其他部分产生影响。在继续前进之前,我会对所有内容进行彻底测试,以确保它不会干扰其他任何东西

标签: reactjs electron


【解决方案1】:

使用react-create-app遇到了同样的问题。

修复,在 React 端使用 window.require 而不是 import

const electron = window.require("electron")

在 Electron 方面,在创建 BrowserWindow 时添加 nodeIntegration: true,如下所示

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

【讨论】:

    【解决方案2】:

    对于打字稿:

    import { IpcRenderer } from 'electron';
    
    declare global {
      interface Window {
        require: (module: 'electron') => {
          ipcRenderer: IpcRenderer
        };
      }
    }
    
    const { ipcRenderer } = window.require('electron');
    

    https://github.com/electron/electron/issues/9920

    【讨论】:

      【解决方案3】:

      以上答案不是最新的。

      正确答案如下:

      从 Electron v12 开始,设置 nodeIntegration: true 没有任何影响。相反,您需要设置contextIsolation: false:

      mainWindow = new BrowserWindow({
          // ...
          webPreferences: {
              contextIsolation: false,
          }
      })
      

      https://github.com/electron/electron/issues/7300#issuecomment-799093768

      【讨论】:

        猜你喜欢
        • 2020-01-07
        • 2011-09-18
        • 1970-01-01
        • 2019-01-05
        • 2018-09-19
        • 2019-02-01
        • 2019-06-12
        • 2017-02-16
        • 1970-01-01
        相关资源
        最近更新 更多