简体   繁体   中英

cannot import electron in react componment for ipcRenderer

So I am trying to import the ipcRenderer into a react component to communicate with the electron side. The issue is I cannot import electron. I tried

import { ipcRenderer } from 'electron/renderer'

returns module electron/renderer not found

import { ipcRenderer } from 'electron'

returns fs.existsSync is not a function

const renderer = require('electron');

returns fs.existsSync is not a function

const renderer = require('electron').ipcRenderer;

returns fs.existsSync is not a function

const renderer = window.require('electron');

returns window.require is not a function

I do not know what to do anymore, I have tried everything

I got it! using electron-react-bolierplate they prepared a custom preload.js script that exposes three functions to the rendered components: myPing : (Just a demo, send a ping message to the console) and exposes the on and once ipcRenderer methods

import { Component } from 'react';
...
...
    class Hello extends Component {
      componentDidMount() {
        console.log('Mounted!', 'Window', window, 'electronApi', window.electron, 'ipcRenderer', window.electron.ipcRenderer);
    
        window.electron.ipcRenderer.on('ipc-example', (arg) => {
          // eslint-disable-next-line no-console
          console.log(arg);
        });
    
        window.electron.ipcRenderer.myPing();
      }
    
      render() {
        return (
          <div>
    ...
    ...

I used to have same problem. You should not import electron directly inside your renderer/react component. Instead in your preload.ts file you are given some basic configuration by electron-react-bolierplate to use.

So inside your react component you should use window.electron.ipcRenderer.on('channel-name', args) sample below

 const myEventHandler = () => { window.electron.ipcRenderer.on('channel-name', (event, data) => { console.log('data, event', data, event); }); };

window.electron, here electron is the name given in preload.ts file. contextBridge.exposeInMainWorld('electron', {...})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM