问题
using a electron, react (es6 / jsx), sass, pouchdb and webpack 2 setup. I fail to import or require ipcRenderer to make communication between main and renderer process possible. My setup can be found here: https://github.com/wende60/timeTracker
Any hints how to get the ipcRenderer into a react component?
Cheers, jo
回答1:
I had the same problem. This solved that issue for me:
Add in the webpack.config.js:
const webpack = require("webpack");
module.exports = {
    plugins: [
        new webpack.ExternalsPlugin('commonjs', [
            'electron'
        ])
    ]
    ...
}
Then you can use it with
import {ipcRenderer} from "electron";
    回答2:
const electron = window.require('electron');
const ipcRenderer  = electron.ipcRenderer;
I think it is the better solution because it avoid ejecting the React app.
回答3:
I suggest you read my response here.
You'll want to set up your app like this:
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);
  });
});
preload.js
** Update: DO NOT use
sendkey value as property name. It will overwrite onwin.webContents.sendmethod and comes to do nothing when you try to callwin.webContents.send('your_channel_name')inside your main processmain.js. Better to use better names likerequestandresponse.
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));
            }
        }
    }
);
index.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>
    回答4:
As of May 2020, I think Erik Martín Jordán has said it best:
Create a preload.js file:
window.ipcRenderer = require('electron').ipcRenderer;
On main.js:
// Create the browser window.
mainWindow = new BrowserWindow({
    alwaysOnTop: true,
    frame: false,
    fullscreenable: false,
    transparent: true,
    titleBarStyle: 'customButtonsOnHover',
    show: false,
    width: 300, 
    height: 350,
    webPreferences: {
        nodeIntegration: true,
        preload: __dirname + '/preload.js'
    }
});
// Blur window when close o loses focus
mainWindow.webContents.on('did-finish-load', () => mainWindow.webContents.send('ping', '🤘') );
mainWindow variable on this file will preload the preload.js file. Now the React component can call the window.ipcRenderer method.
In the React app.js:
import React, { useEffect, useState } from 'react';
import './App.css';
function App() {
    useEffect( () => {
        window.ipcRenderer.on('ping', (event, message) => { 
            console.log(message) 
        });
    }, []);
    return (
    <div className = 'App'></div>
    );
}
export default App;
    回答5:
Found a good solution for this issue using webpack-target-electron-renderer So I can develop the web-part in a localhost environment with hot-reloading. electron is required only in the electron environment.
You can see a working example here: https://github.com/wende60/webpack-web-and-electron-example, forked from acao's webpack-web-and-electron-example and updated for webpack 2 and hot-replacement.
If you are interested in a webpack, electron, react, sass and pouchdb setup have a look here: https://github.com/wende60/timeTracker Work is still in progress...
回答6:
I've been looking into this topic just recently and I found a solution for doing some some ipc between electrons main.js and the React part of the application. Since both, import {ipcRenderer} from 'electron'; after adding the plugin to the webpack modules and const ipc = require('electron').ipcRenderer; produced some errors I ended up requiring electron in the resulting page and adding it to the window.
In the index.html I did something like this
<body>
  ...
  <script>
    window.ipc = require('electron').ipcRenderer;
  </script>
  <div id="root">
  </div>
  ...
</body>
In reacts index.js I did something like this:
import React from 'react';
import ReactDOM from 'react-dom';
// ...
if(window.ipc)
ipc.on("some-event", (event, someParameter) => {
  ReactDOM.render(
    <SomeElement value={someParameter} />,
    document.getElementById("root")
  );
})
// ...
In order to make this work i started the react page from the electron app, in the main.js I did something like that.
const {app, BrowserWindow} = require("electron"};
const exec = require("child_process").exec;
let main;
app.on("ready", () => {
  exec("node start", (err, stdout, stderr) => {
    if(err) console.log(err);
    console.log("" + stdout);
    console.log("" + stderr);
  });
  main = new BrowserWindow();
  main.loadURL("http://localhost:3006");
  main.on("close", () => {main = null});
});
because electron is running on the same port I added a .env file to my project that contained
PORT=3006
I used the create-react-app my-prj (npm install -g create-react-app) command for my base project it looked something like this
my-prj
 |-package.json
 |-main.js
 |-.env
 |-node_modules/
 |-public/
    |-index.html
 |-src/
    |-index.js
Hope this post was of any help.
回答7:
import { ipcRenderer } from "electron"
import { Component } from "react"
...
class MyComponent extends Component {
   render(){
      ipcRenderer.send("event", "some data")
      return (<div>Some JSX</div>)
   }
}
    来源:https://stackoverflow.com/questions/44008674/how-to-import-the-electron-ipcrenderer-in-a-react-webpack-2-setup