11

I am developing an electron app. All good and nice until I wanted to use IPC from the renderer to call some native features. I understand that adding the following line to my Webpack config would allow me to import electron on the renderer side.

module.exports = {
    // ...
    target: 'electron-renderer',
}

I get the following error when adding this line

Uncaught ReferenceError: require is not defined

And the offending line is

module.exports = require("querystring");

Which sort of makes sense, since the browser does not understand "requires".

Note that without the electron-renderer target the application works well, except I cannot do things like

import {ipcRenderer} from 'electron';

Any thoughts what I could be doing wrong? Thank you!

3 Answers 3

16

Just recently ran into this. One thing to look out for is to ensure nodeIntegration is set to true when creating your renderer windows.

mainWindow = new electron.BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
        nodeIntegration: true
    }
});
5
  • 11
    Note that nodeIntegration: true is generally INSECURE. electronjs.org/docs/tutorial/security
    – Luke H
    Aug 31, 2019 at 16:02
  • @AndreiCioara would love to know if you solved this mate, nodeIntegration: true was already true for me and I'm getting this error.
    – jflood.net
    Dec 13, 2020 at 8:42
  • 3
    So FYI, every single article on this topic says the same thing - set nodeIntegration to true. What do you do when nodeIntegration is, and has been set to true, yet "require is not defined" still occurs?
    – JimboTwice
    Jan 20, 2021 at 17:37
  • 2
    I too am still having this issue and nodeIntegration is set to true also. Jan 22, 2021 at 19:11
  • 10
    I was struggling with this issue myself, still getting "require is not defined" with nodeIntegration: true. Setting contextIsolation: false as well got it to start working for me. Mar 3, 2021 at 19:41
14

Also faced this issue, new answer:

mainWindow = new electron.BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
    }
});
1

AFAIU the recommended way is to use contextBridge module (in the preload.js script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.

https://www.electronjs.org/docs/latest/tutorial/context-isolation

Following this way, I also found that it was no longer necessary to specify target property in the Webpack config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.