現在需要做一個桌面應用,心里有點不甘,因為想做出一個簡單的客戶端,你要么使用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運行就好了