解决Electron5.xrequireisnotdefined报错问题

2022-5-16 18:49| 发布者: Hocassian| 查看: 108| 评论: 0|原作者: 梓喵出没

摘要:
C:\Users\Administrator\Downloads\2019-10-13-23-2-14-129306659666100-文章归档 梓喵出没-采集的数据-后羿采集器.html

标题

解决Electron 5.x require is not defined 报错问题

链接

https://www.azimiao.com/4845.html

阅读量

153 人阅读

日期时间

2019-5-20

作者

梓喵·技术

正文

升级了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


路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部