electron 加载node.jsAPI模块报错
1、错误提示:Uncaught ReferenceError: require is not defined at(未捕获的引用错误:未在处定义Require)
原因:electron升级到5.0之后默认关闭了html页面启用nodejs环境的问题,electron中文官网里的API提示是默认开启(webPreferences=>nodeIntegration)
解决方法:
具体的设置方式应该是在主进程main.js里实例化BrowserWindow时打开配置:
//主进程
//引入electron模块
var electron = require('electron');
var path = require('path');
//创建electron引用
var app = electron.app;
//创建electron BrowserWindow的引用
var BrowserWindow = electron.BrowserWindow;
//创建一个变量 mainWidow 保存对应用窗口的引用
var mainWidow = null;
//监听ready事件
app.on('ready',()=>{
//创建BrowserWindow实例 赋值给 mainWidow 打开窗口
//设置默认打开的窗口大小为400x400
mainWidow = new BrowserWindow({
width:800,
height:600,
webPreferences:{
nodeIntegration:true, //设置开启nodejs环境
}
});
//加载初始页面
// mainWidow.loadFile('index.html');
mainWidow.loadURL(path.join('file:',__dirname,'index.html'));
//开启渲染进程中的调试模式
mainWidow.webContents.openDevTools();
//监听窗口关闭 销毁引用
mainWidow.on('close',()=>{
mainWidow = null;
})
});
创建BrowserWindow的时候指定nodeIntegration为false。 这样在electron内置浏览器里面不会有module和require全局变量
2.electron 10版本

解决办法:
而在主进程中我们需要向webPreferences配置参数enableRemoteModule:true来打开remote模块,使得渲染进程中可以调用主进程的方法,我们需要对mianWindow来配置
mainWindow = new BrowserWindow({
width:600,
height:800,
/* 启用Node继承 */
webPreferences:{
nodeIntegration:true,
enableRemoteModule:true,//设置开启remote模块
}
})