Electron是一个可以使用 JavaScript,HTML 和 CSS 构建跨平台桌面应用程序的开源框架。

本文主要记录一下采用vue + electron开发桌面程序的搭建过程。

1. 环境准备

这里采用的是vue-cli3.x,可以通过下面的指令查看当前vue-cli的版本:



vue --version# 3.9.3 这里我用的是3.9.3

如果没有装vue-cli可以通过下面的命令安装:


npm install -g @vue/cli

如果是vue-cli还是2.x可以先卸载2.x然后装3.x



npm uninstall vue-cli -gnpm install -g @vue/cli

2. 创建项目

这里采用vue-cli创建vue项目。


vue create electron-helloworld

引入vue-cli-plugin-electron-builder



cd electron-helloworldvue add electron-builder

这一步需要拉取electron-vX.Y.Z-win32-x64.zip,过程非常漫长。

3. 运行项目

项目创建完成后就可以运行electron项目。


npm run electron:serve

4. node通讯

正常来说vue组件应该只关心页面层的逻辑即可,所以为了解耦,可以在 VueComponentNodeAPIElectronAPI中间插入一个桥接层,然后通过IPC进行通讯,如下图所示:

使用Electron开发桌面应用_java

按照关系图, VueCommponent通过 Service发布事件,完成与 NodeAPIElectronAPI的通讯,下面根据这个关系写一个读取文件内容的示例。

创建Service,发布事件并监听

/bridge/service/Service.js


import { ipcRenderer } from 'electron'class Service {  readTxt(params, callback) {    ipcRenderer.once('readTxt', (e, ret) => callback(ret))    // 将params参数传给Server    ipcRenderer.send('readTxt', params)  }}export default new Service()

创建Server,监听事件并读取文件内容返回

/bridge/server/Server.js


import { ipcMain } from "electron";import fs from 'fs'export default class Server {  constructor(app, win) {    this.app = app    this.win = win  }  initEventHandler() {    ipcMain.on('readTxt', (e, params) => {      // 这里将参数转化为json,然后读取G:\\0.txt的内容一起返回      const pms = JSON.stringify(params)      const ret = fs.readFileSync('G:\\0.txt')      e.sender.send('readTxt', pms + '::::' + ret)    })  }}

启动Server

在创建完Server之后,需要在应用程序启动的时候启动并让其监听对应的事件。

这里可以创建一个ApplicationContext,来启动Server。

/bridge/ApplicationContext.js


import Server from './server/Server'export default class ApplicationContext {  constructor(app, window) {    this.app = app    this.window = window  }  init() {    new Server(this.app, this.window).initEventHandler()  }}

然后在background.js中实例化ApplicationContext,并调用init方法。


  win.on('closed', () => {    win = null  })  // Windows创建完成后初始化context  new ApplicationContext(app, win).init()

Vue组件调用Service

完成上面三步之后,只需要在vue组件中调用Service即可,这一步跟普通开发vue程序是一样的。



<div>{{txt}}</div><button @click="readTxt">读取文件信息</button>

javascript代码


<script>import service from '@/bridge/service/Service'export default {  name: 'HelloWorld',  props: {    msg: String  },  data() {    return {      txt: ''    }  },  methods: {    readTxt() {      // 这里传入两个参数,并将返回结果赋值给txt,在div中显示出来      service.readTxt({        p1: '参数1',        p2: '参数2'      }, resp => {        this.txt = resp      })    }  }}</script>

至此,一个electron helloworld示例就完成了。

5. node API undefind

在上面的过程中可能会遇到node API undefined的情况,这是因为electron禁用了node集成,在background.js中创建window的时候指定了配置:


webPreferences: {      // Use pluginOptions.nodeIntegration, leave this alone      // See nklayman.github.io/vue-cli-plugin-electron builder/guide/security.html#node-integration for more info      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION     // nodeIntegration: true}

这里可以通过配置 electronBuilder插件解决。

在项目目录根目录下面创建 vue.config.js,内容如下:


// see https://cli.vuejs.org/configmodule.exports = {  productionSourceMap: false,  pluginOptions: {    electronBuilder: {      nodeIntegration: true,    },    configureWebpack: {      resolve: {        symlinks: true      }    }  }}