question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to use ipcRenderer in EF + TS + React without nodeIntegration: true

See original GitHub issue

Preflight Checklist

  • I have read the contribution documentation for this project.
  • I agree to follow the code of conduct that this project follows, as appropriate.
  • I have searched the issue tracker for a bug that matches the one I want to file, without success.

Issue Details

  • Electron Forge Version:
    • 6.0.0-beta.54
  • Electron Version:
    • 11.2.3
  • Operating System:
    • macOS 10.15.7

Expected Behavior

I am using Electron Forge with TypeScript and React. I attempted to import "electron" into my renderer.tsx file because I want to have a functionality that allows a button click event to communicate with the main process.

// renderer.tsx
class Button extends React.Component
{
    constructor(props: unknown)
    {
        super(props);
        this.onClick = this.onClick.bind(this);
    }
    onClick(): void
    {
        Electron.ipcRenderer.send("button");
    }
    render(): JSX.Element
    {
        return (<button onClick={this.onClick}>run</button>);
    }
}

// index.ts
function button(): void
{
    console.log("Button clicked");
}
Electron.ipcMain.on("button", button);

// package.json
"mainConfig": "./webpack.main.config.js",
"renderer": {
    "config": "./webpack.renderer.config.js",
    "entryPoints": [
        {
            "html": "./app/index.html",
            "js": "./app/renderer.tsx",
            "name": "main_window"
        }
    ]
}

Actual Behavior

Electron starts the app, but the renderer process crashes due to failing to import Electron in the renderer.tsx file. The error given in the console is

Uncaught ReferenceError: require is not defined
    at Object.electron (external "electron":1)
    at __webpack_require__ (bootstrap:789)
    at fn (bootstrap:100)
    at Object.<anonymous> (renderer.tsx:5)
    at Object../app/renderer.tsx (renderer.tsx:38)
    at __webpack_require__ (bootstrap:789)
    at fn (bootstrap:100)
    at Object.0 (module.js:22)
    at __webpack_require__ (bootstrap:789)
    at bootstrap:856

This issue can be fixed by setting nodeIntegration: true when creating the window, however this is a security risk and is heavily discouraged.

To Reproduce

The repository here should be able to reproduce this issue.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

9reactions
rsathishtechitcommented, Jul 29, 2021

Using preload option provided by @electron-forge/plugin-webpack could solve this problem

In package.json

"plugins": [
        [
          "@electron-forge/plugin-webpack",
          {
            "mainConfig": "./webpack.main.config.js",
            "renderer": {
              "config": "./webpack.renderer.config.js",
              "entryPoints": [
                {
                  "html": "./src/index.html",
                  "js": "./src/renderer.js",
                  "name": "main_window",
                  "preload": {
                    "js": "./src/preload.js"
                  }
                }
              ]
            }
          }
        ]
      ]

src/preload.js

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

contextBridge.exposeInMainWorld("electron", {
  notificationApi: {
    sendNotification(message) {
      ipcRenderer.send("notify", message);
    },
  },
  batteryApi: {},
  fileApi: {},
});

main.js

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      worldSafeExecuteJavaScript: true,
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
    },
  });

  // and load the index.html of the app.
  mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};


ipcMain.on("notify", (_, message) => {
  new Notification({ title: "Notification", body: message }).show();
});
/

src/app.jsx

import * as React from "react";
import * as ReactDOM from "react-dom";

class App extends React.Component {
  componentDidMount() {
    electron.notificationApi.sendNotification("Finally!");
  }
  render() {
    return <h1>contextBridge</h1>;
  }
}

ReactDOM.render(<App />, document.body);

The above method works with the React+Webpack template.

4reactions
maleptcommented, Feb 12, 2021

If you wish to use ipcRenderer when nodeIntegration is false, you’ll need to use preload scripts.

FYI, this isn’t a issue that’s specific to Electron Forge. If you need more assistance, please use one of Electron’s community forums.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to use ipcRenderer in EF + TS + React without ...
This issue can be fixed by setting nodeIntegration: true when creating the window, however this is a security risk and is heavily discouraged....
Read more >
Electron Forge - Can't use ipcRenderer in the renderer file
Found Solution. The solution is to use ipcRenderer in a preload script. preload.ts import { ipcRenderer } from "electron";. index.ts
Read more >
Security | Electron
A set of guidelines for building secure Electron apps.
Read more >
Require Is Not Defined In A Electron-React-Webpack ...
existsSync is not a function | import { ipcRenderer } from 'electron', ... type Unable to use ipcRenderer in EF + TS +...
Read more >
Electron and TypeScript: how to use ipcMain and ipcRenderer ...
I was using preload.ts to ensure an interface between Svelte and ... webPreferences: { nodeIntegration: false, contextIsolation: true, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found