Electron Require() Is Not Defined

Electron require() is not defined

As of version 5, the default for nodeIntegration changed from true to false.
You can enable it when creating the Browser Window:

app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
});

Uncaught ReferenceError: require not defined (electron)

Since Electron 5, Node integration in the renderer process is disabled by default. To get around that, you need to declare nodeIntegration: true when instantiating your BrowserWindow.

// In the main process.
const { BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})

Edit: As of Electron 12, you'll also need to define contextIsolation: false in order to do this, as the default value of the flag has changed.

https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true

Uncaught ReferenceError: require is not defined in Electron BrowserWindow

contextIsolation is enabled, disable contextIsolation and nodeIntegration should work.

webPreferences: {
nodeIntegration: true,
contextIsolation: false
}

Electron Uncaught ReferenceError: require is not defined | I have nodeIntegration set to true

I have had the same issue.
It comes with the update from electron 11.x to 12.x See here: https://www.electronjs.org/releases/stable#release-notes-for-v1200

You have to disable contextisolation, which changed from beeing true by default in the new electron version.

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})

win.loadFile('index.html')
}

Another solution is to downgrade to electron 11.x where contextIsolation: false is the default.

My sources:
https://www.reddit.com/r/electronjs/comments/lxjva0/required_not_defined_but_nodeintegration_set_to/
Picture of electron Changelog

electron 5.0.0 Uncaught ReferenceError: require is not defined

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


Related Topics



Leave a reply



Submit