升级了Electron 5.0.1,发现之前的代码跑不动了,前端页面报错:require is not defined。谷歌搜了下,解决了这个问题。

错误代码示例

后端 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();
});

前端 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>

保存之后运行Electron,前端页面有如下报错:

解决问题

在Electron5.0中,BrowserWindow的nodeIntegration默认为false,而4.x版本中这个值默认为true。在构造参数中传入true,就能使用require了。

修改main.js对应部分如下:

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

保存后运行,控制台正常输出Hello World

梓喵出没博客(azimiao.com)版权所有,转载请注明链接:https://www.azimiao.com/4845.html
欢迎加入梓喵出没博客交流群:313732000

我来吐槽

*

*

0位绅士参与评论

  1. 蝉時雨05-29 00:04 回复

    前段时间初学 Electron 写了个本地漫画图片阅读器,踩了一堆坑 😕