Electron跨平台桌面级应用开发框架
上次我们提到了业界大名鼎鼎的Qt桌面级应用开发框架,不过Qt是基于c++进行开发的,c++的开发模式也并不是十分适用于现代这种短平快的软件开发模式,相比之下,electron是基于nodejs和 Chromium使用javascript,html和css来开发桌面应用的框架。
Electron的原理很简单,基本上就是使用我们常见的chrome浏览器的内核为基础通过nodejs和底层操作系统进行操作交互。
通过快速开始了解Electron
准备
必要的准备内容不多,不管你是windows,linux还是mac只要安装最新版本的nodejs就可以了,除此之外确保你有npm和git
然后打开命令提示符输入
# 克隆electron快速开始的源
git clone https://github.com/electron/electron-quick-start
# 进入到electron快速开始的文件夹
cd electron-quick-start
# 安装依赖和运行APP
npm install && npm start
安装依赖的过程可能比较久,npm会自动安装一些windows的编译包。
安装成功并且运行了会提示入下图

实际上就是个chrome浏览器的壳子把html和css以及js绘制的UI显示出来,右边的debug工具都是和chrome里一模一样的。

当然我们也可以关闭它。显示的时候看起来就更加像是一个浏览器了。
electron目录结构
electron的目录结构如下。
your-app/
├── package.json
├── main.js
└── index.html
package.json
package.json是我们常见的npm包管理软件,这里主要是一些APP的应用信息,包的管理和开发用的脚本命令。在这里我们还要定义好main为main.js如果没有定义的话会默认启动index.js。这里和nodejs默认的情况都差不多。
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
main.js
main.js是应用程序的主进程文件,这个主进程文件就是用来创建应用程序窗口和处理系统事件使用的文件。它看起来大概是下面这个样子。
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
mainWindow.webContents.openDevTools()
// 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
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
index.html
这个文件显示主界面的信息内容。

就是图中红色箭头指示的位置。
总结
electron想必qt开发起来就容易多了,因为我们可以通过html,css和javascript这样简单容易的语言开发跨平台的桌面应用,因为读取的是html文件,这还意味着我们可以更容易的在服务端实时更新数据内容。