Solve the problem of error reported by Electron 5. x require is not defined

Share

Upgraded Electron 5.0.1 It was found that the previous code could not run, and the front page reported an error: require is not defined . Google searched and solved this problem.

Error code example

Back end main.js

 const{app,ipcMain,BrowserWindow } = require("electron"); let mainWindow; function CreateWindow(){ mainWindow = new BrowserWindow({ width:800, height:600 }); mainWindow.loadFile("./html/index.html"); } ipcMain.on("Test",(sender,args)=>{ console.log(args); }) app.on("ready",()=>{ CreateWindow(); });

Front index.html

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> const {ipcRenderer} = require("electron"); </script> </head> <body> <script> ipcRenderer.send("Test","Hello World");      </script> </body> </html>

After saving, run Electron. The front page reports the following error:

solve the problem

In Electron5.0, the BrowserWindow's nodeIntegration Default is false In version 4. x, the default value is true . Pass in true in the construction parameter to use require.

Modify the corresponding part of main.js as follows:

 mainWindow = new BrowserWindow({ width:800, height:600, webPreferences: { nodeIntegration: true } });

Run after saving, and the console outputs normally Hello World