I had initially been using electron stable (4.x.x), and was able to use require
in both my browser and renderer processes. I upgraded to electron beta (5.0.0) because I needed a newer version of node and encountered this error message in my renderer process, Uncaught ReferenceError: require is not defined
.
Googling and looking through the electron docs, I found comments saying the error could be caused by setting webPreferences.nodeIntegration
to false when initializing the BrowserWindow
; e.g.: new BrowserWindow({width, height, webPreferences: {nodeIntegration: false}});
. But I was not doing this, so I thought something else must be the issue and continued searching for a resolution.
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
Summary A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node. js environment, and is often used to expose privileged APIs to the renderer via the contextBridge API.
Electron node integration refers to the ability of accessing Node. js resources from within the “renderer” thread (the UI). It is enabled by default in Quasar CLI, although Electron is encouraging developers to turn it off as a security precaution.
@electron/remote is an Electron module that bridges JavaScript objects from the main process to the renderer process. This lets you access main-process-only objects as if they were available in the renderer process.
For Electron version 12 and above
const electron = require("electron"); const { app, BrowserWindow } = electron; app.on("ready", () => { const mainWindow = new BrowserWindow({ width: 1000, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true, }, }); mainWindow.loadURL(`file://${__dirname}/index.html`); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With