如何在react/webpack 2设置中导入电子ipcRenderer

Joa*_*him 8 reactjs webpack electron

使用电子,反应(es6/jsx),sass,pouchdb和webpack 2设置.我无法导入或要求ipcRenderer在主进程和渲染器进程之间进行通信.我的设置可以在这里找到:https://github.com/wende60/timeTracker

任何提示如何将ipcRenderer放入反应组件?

干杯,乔

Zac*_*Zac 10

我建议你在这里阅读我的回复。

您需要像这样设置您的应用程序:

main.js

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

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

async function createWindow() {

  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // is default value after Electron v5
      contextIsolation: true, // protect against prototype pollution
      enableRemoteModule: false, // turn off remote
      preload: path.join(__dirname, "preload.js") // use a preload script
    }
  });

  // Load app
  win.loadFile(path.join(__dirname, "dist/index.html"));

  // rest of code..
}

app.on("ready", createWindow);

ipcMain.on("toMain", (event, args) => {
  fs.readFile("path/to/file", (error, data) => {
    // Do something with file contents

    // Send result back to renderer process
    win.webContents.send("fromMain", responseObj);
  });
});
Run Code Online (Sandbox Code Playgroud)

预加载.js

** 更新:不要使用send键值作为属性名称。win.webContents.send当您尝试win.webContents.send('your_channel_name')在主进程内部调用时,它将覆盖方法并且不执行任何操作main.js。最好使用更好的名称,例如requestresponse

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        //send: (channel, data) => {
        request: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        //receive: (channel, func) => {
        response: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

索引.html

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="utf-8"/>
    <title>Title</title>
</head>
<body>
    <script>
        window.api.response("fromMain", (data) => {
            console.log(`Received ${data} from main process`);
        });
        window.api.request("toMain", "some data");
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


Mat*_*ias 8

我有同样的问题。这为我解决了这个问题:

添加在webpack.config.js

const webpack = require("webpack");

module.exports = {
    plugins: [
        new webpack.ExternalsPlugin('commonjs', [
            'electron'
        ])
    ]
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它

import {ipcRenderer} from "electron";
Run Code Online (Sandbox Code Playgroud)


eco*_*coe 6

截至 2020 年 5 月,我认为Erik Mart\xc3\xadn Jord\xc3\xa1n 说得最好

\n

创建 preload.js 文件:

\n
window.ipcRenderer = require(\'electron\').ipcRenderer;\n
Run Code Online (Sandbox Code Playgroud)\n

在 main.js 上:

\n
\n// Create the browser window.\nmainWindow = new BrowserWindow({\n    alwaysOnTop: true,\n    frame: false,\n    fullscreenable: false,\n    transparent: true,\n    titleBarStyle: \'customButtonsOnHover\',\n    show: false,\n    width: 300, \n    height: 350,\n    webPreferences: {\n        // UPDATE: for electron > V12 consider setting contextIsolation and see: https://github.com/electron/electron/issues/9920#issuecomment-797491175\n        nodeIntegration: true,\n        preload: __dirname + \'/preload.js\'\n    }\n});\n\n// Blur window when close o loses focus\nmainWindow.webContents.on(\'did-finish-load\', () => mainWindow.webContents.send(\'ping\', \'\') );\n
Run Code Online (Sandbox Code Playgroud)\n

该文件上的 mainWindow 变量将预加载 preload.js 文件。现在React组件可以调用window.ipcRenderer方法了。

\n

在 React app.js 中:

\n
import React, { useEffect, useState } from \'react\';\nimport \'./App.css\';\n\nfunction App() {\n    \n    useEffect( () => {\n        \n        window.ipcRenderer.on(\'ping\', (event, message) => { \n            console.log(message) \n        });\n                \n    }, []);\n            \n    return (\n    <div className = \'App\'></div>\n    );\n}\n\nexport default App;\n
Run Code Online (Sandbox Code Playgroud)\n


小智 5

const electron = window.require('electron');
const ipcRenderer  = electron.ipcRenderer;
Run Code Online (Sandbox Code Playgroud)

我认为这是更好的解决方案,因为它避免弹出React应用程序。


Sat*_*ors -4

import { ipcRenderer } from "electron"
import { Component } from "react"
Run Code Online (Sandbox Code Playgroud)

...

class MyComponent extends Component {
   render(){
      ipcRenderer.send("event", "some data")
      return (<div>Some JSX</div>)
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨,Sators,这是我 - 当然 - 之前尝试过的东西,但我最终得到了类似的东西: **bundle.js:49593 Uncaught Error: Cannot find module "fs"** at webpackMissingModule (bundle.js:49593 ) 在 Object.&lt;anonymous&gt; (bundle.js:49593) 在 Object.splitPathRe (bundle.js:49604) 在 __webpack_require__ (bundle.js:658) 在 fn (bundle.js:86) ... **npm install fs** 不是这里的解决方案...... (3认同)