"Uncaught ReferenceError: require is not defined"

I’m a starter in electron, but I got “Uncaught ReferenceError: require is not defined” when I start the program. My code is below:

main.js

const {
    app,
    BrowserWindow,
    Menu,
    ipcMain,
    screen
} = require('electron');
const url = require('url');
const path = require('path');

function createWindow(file, params = {}) {
    const win = new BrowserWindow(params);

    win.loadURL(url.format({
        pathname: path.join(__dirname, file),
        protocol: "file",
        slashes: true
    }));

    return win;
}

ipcMain.on("addRecipe", (e) => {
    createWindow("", {
        height: 640,
        width: 360,
        webPreferences: {
            nodeIntegration: true
        }
    });
});

app.on("ready", () => {
    const {
        width,
        height
    } = screen.getPrimaryDisplay().workAreaSize;
    let main = createWindow("index.html", {
        width: width,
        height: height,
        webPreferences: {
            nodeIntegration: true
        }
    });
    Menu.setApplicationMenu(Menu.buildFromTemplate([{
        label: "Dev Tools",
        accelerator: "Ctrl+Shift+I",
        click(i, fw) {
            fw.toggleDevTools();
        }
    }]));
    
    app.on('activate', function() {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

app.on('window-all-closed', function() {
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

If you notice, I have nodeIntegration: true. Why is this still not working?

Hi @Cutewarriorlover.

I copy-pasted your main.js code into electron-fiddle and ran it with electron 12.0.0. It worked for me. (It didn’t work with Electron 6.1.12, though.)

I wonder if you’re using a recent stable version of Electron or something else? What command are you running where you get that error?

Ah, I got the answer from stackoverflow. Apparently, I need to manually toggle contextIsolation off. Thanks for your answer though.