从零开发Electron-Vue (四) 最新2021electron-vue项目实际碰到的问题

问题:在build成功后回过头来发现不能run electron:serve了,有俩个错误,第一个报DEVTOOLS相关的错

解决方法:在background.js里注释掉与VUEJS_DEVTOOLS相关的东西

// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'

app.on('ready', () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
})

再加一个
const win = new BrowserWindow({
    webPreferences: {
      contextIsolation: false
    }
  })

 第二个是eslint的

 创建vue.config.js,增加

module.exports = {
    lintOnSave: false
}

 问题:在electron版本大于10.0.0当前项目,不能获取到shell等任何对象。。。

const shell = require('electron').shell;
shell.openExternal('http://www.baidu.com');
这样的写法会报shell是个undefined

 解决方案:

const {shell} = window.require('electron').remote;
shell.openExternal('http://www.baidu.com');
然后在background.js里增加
const win = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true, // 是否集成 Nodejs
      enableRemoteModule: true,
    }

 解决方案2:

将@vue/cli的版本降低为4.0.5后,渲染进程使用require(‘electron’)完美获取到相应对象
vue/cli卸载命令
npm uninstall -g @vue/cli
vue/cli安装老版本命令
npm install -g @vue/cli@4.0.5

创建vue.config.js 文件,并增加以下内容:
module.exports = {
pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      }
 }
}

 问题:将需要用到Node.js API和Electron API 的方法抽象到renderer.js, 从HTML中单独引入,也就避免了webpack对renderer.js进行处理。然后通过插件的方式引入到前端框架中,以Vue为例:

 index.html

<script src="renderer.js"></script><!--提供Render Process 方法 -->
<script src="./dist/build.js"></script><!--webpack 打包文件-->

renderer.js

const electron = require('electron');
const remote = electron.remote;
const remoteApi = remote.require('./api.js');

global.remoteApi = remoteApi;

Vue入口文件main.js

Vue.use({
    install (Vue, options) {
        //添加实例方法
        Vue.prototype.$remoteApi = global.remoteApi;
    }
});

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值