环境:
electron版本:18.0.0
node.js版本:16.14.2
vue:3.x
问题一:require is not defined。
需要将位于main.js中的webPreferences中的contextIsolation置为false,才能将使用node的require,配置如下:
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}});
问题二:高版本创建remote的问题
描述:在低版本的时候,创建remote:
const remote = require('electron');
在高版本已经把remote单独出来了,在渲染进程创建remote,这个remote就会变成undifined。解决方法:
第一步:对18.0.0来说需要先下载 @electron/remote
npm install --save @electron/remote
创建remote需要在main.js中打开enableRemoteModule选项,也就是需要将位于main.js中的webPreferences中的enableRemoteModule置为true,配置如下:
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}});
第二步:需要在app.on('ready')的方法中加入两条初始化remote的语句
require('@electron/remote/main').initialize()
require("@electron/remote/main").enable(mainWindow.webContents)
app.on('ready')配置如下:
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}});
require('@electron/remote/main').initialize()
require("@electron/remote/main").enable(mainWindow.webContents)
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
然后就可以在渲染进程使用remote来使用各组件。比如:
const remote = require("@electron/remote")
const {Menu, MenuItem, dialog,desktopCapturer } = remote