现在需要做一个桌面应用,心里有点不甘,因为想做出一个简单的客户端,你要么使用Java的Swing编程,要么会使用MFC等等,这样学习的代价太高,也不便维护,于是了解了一下Electron,Electron提供了丰富的本地(操作系统)的API,使你能够使用纯JavaScript来创建桌面应用程序。与其它各种的Node.js运行时不同的是Electron专注于桌面应用程序而不是Web服务器,这并不意味着Electron是一个绑定图形用户界面(GUI)的JavaScript库,取而代之的是,Electron使用Web页面作为它的图形界面,所以你也可以将它看作是一个由JavaScript控制的迷你的Chrominum浏览器,像钉订客户端就是使用这种方式开发的,但是是使用的nw.js,我想要去学习和掌握的是Electron,ATOM就是这样造出来的。
去官网下载并解压打开electron弹出如下界面
这样最简单的就给你安装好了electron的环境了,现在就可以开始写一个桌面程序,然后拖入它打开就好了,当然也可以去按照官网的说明使用npm下载
现在来书写第一个应用hello world
通常,一个Electron应用的结构类似下面:
your-app/
├── package.json
├── main.js
└── index.html
package.json 的格式与Node的模块格式是一致的,其中 main 字段指定的脚本就是你应用的启动脚本,该脚本将运行在主进程中。你的 package.json 也许看上去像下面这个例子:
{ "name" : "your-app", "version" : "0.1.0", "main" : "main.js" }
注意 如果在 package.json 中的 main 字段没有指定,那么Electron将尝试装载一个名为 index.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 则是你想要展示在窗口中:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </body> </html>
然后拖入electron运行就好了