Andrei Cioara
Andrei Cioara

Reputation: 3664

'Require is not defined' when adding electron-renderer to webpack

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!

Upvotes: 11

Views: 9246

Answers (3)

keV
keV

Reputation: 33

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.

Upvotes: 1

lygstate
lygstate

Reputation: 562

Also faced this issue, new answer:

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

Upvotes: 14

Brian DiCasa
Brian DiCasa

Reputation: 9487

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
    }
});

Upvotes: 16

Related Questions