使用Electron開發桌面應用


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 -g
npm install -g @vue/cli

2. 創建項目

這里采用vue-cli創建vue項目。

vue create electron-helloworld

引入vue-cli-plugin-electron-builder

cd electron-helloworld
vue add electron-builder

這一步需要拉取electron-vX.Y.Z-win32-x64.zip,過程非常漫長。

3. 運行項目

運行electron項目。

npm run electron:serve

Electron

4. node通訊

正常來說vue組件應該只關心頁面層的邏輯即可,所以為了解耦,可以在Vue ComponentNode APIElectron API中間插入一個橋接層,然后通過IPC進行通訊,如下圖所示:

IPC

按照關系圖,Vue Commponent通過Service發布事件,完成與Node APIElectron API的通訊,下面根據這個關系寫一個讀取文件內容的示例。

創建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>
<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/config
module.exports = {
  productionSourceMap: false,
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
    },
    configureWebpack: {
      resolve: {
        symlinks: true
      }
    }
  }
}

項目源碼可關注公眾號 “HiIT青年” 發送 “electron-helloworld” 獲取。(如果沒有收到回復,可能是你之前取消過關注。)

HiIT青年
關注公眾號,閱讀更多文章 (如打包成exe,版本自動升級)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM