electron开发过程碰到的问题

环境:

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值