一口氣完成electron的入門學習

介紹

目前,使用前端技術開發桌面應用已經愈來愈成熟,這使得前端同窗也能夠參與桌面應用的開發。目前相似的工具備electron,NW.js等。這裏咱們着重介紹下electron。javascript

electron開發

electron是基於Node.js和Chromium作的一個工具。electron是的可使用前端技術實現桌面開發,而且支持多平臺運行。下面來說下如何使用electron開發桌面app。html

hello world

一個最簡單的electron項目包含三個文件, package.json, index.html, main.js
package.json是Node.js項目的配置文件,index.html是桌面應用的界面頁面,main.js是應用的啓動入口文件。其中,核心的文件是inde.htmlmain.js,下面來說下這兩個文件的細節。
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>

main.js是electron應用的入口文件。主要用戶啓動electron的界面。能夠經過如下代碼來啓動electron界面。java

const electron = require('electron');
const { app } = electron;
const { BrowserWindow } = electron;
let win;
function createWindow() {
  // 建立窗口並加載頁面
  win = new BrowserWindow({width: 800, height: 600});
  win.loadURL(`file://${__dirname}/index.html`);

  // 打開窗口的調試工具
  win.webContents.openDevTools();
  // 窗口關閉的監聽
  win.on('closed', () => {
    win = null;
  });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});

上面的代碼就實現了一個hello world的electron應用。代碼寫完後,須要運行代碼看看效果,這個時候須要使用electron-prubuilt來運行代碼。
首先,咱們須要安裝electron-prubuilt包。能夠經過命令npm install --saved-dev electron-prebuilt進行安裝。安裝完成後,項目本地就可使用electron命令,直接運行命令electron .就能夠看到hello world的效果。或者能夠在package.json中設置scripts,方便項目的運行。
具體代碼能夠去這裏獲取。node

主進程與渲染進程

electron中,由package.json中的main.js運行出來的進程爲主進程(Main Process)。主進程用於建立GUI界面以便web頁面的展現。electron由Chromium負責頁面的顯示,因此當建立一個頁面時,就會對應的建立渲染進程(Renderer Process)。
主進程經過建立BrowserWindow對象來建立web顯示頁面,BrowserWindow運行在他本身的渲染進程中。當BrowserWindow被銷燬時,對應的渲染進程也會終止。 linux

在渲染進程中,直接調用原生的GUI接口是十分危險的。若是你想在渲染進程中使用原生的GUI的功能,須要讓渲染進程與主進程進行通訊,再由主進程去調用對應接口。那麼主進程和渲染進程是如何進行通訊的呢?
electron中,主進程與渲染進程的通訊存在多種方法。這裏介紹一種,經過ipcMainipcRenderer對象,以消息的方式進行通訊。
先來看下主進程如何向渲染進程發信息。
首先,渲染進程經過接口ipcRenderer.on()來監聽主進程的消息信息。主進程經過接口BrowserWindow.webContents.send()向全部渲染進程發送消息。相關代碼以下:git

// renderer.js
// 引入ipcRenderer對象
const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;
// 設置監聽
ipcRenderer.on('main-process-messages', (event, message) => {
  console.log('message from Main Process: ' , message);  // Prints Main Process Message.
});

// main.js
// 當頁面加載完成時,會觸發`did-finish-load`事件。
win.webContents.on('did-finish-load', () => {
  win.webContents.send('main-process-messages', 'webContents event "did-finish-load" called');
});

那麼渲染進程須要給主進程發生消息該如何作呢?github

// renderer.js
ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log('asynchronous-reply: %O %O', event, arg);
});
ipcRenderer.send('asynchronous-message', 'hello');

// main.js
ipcMain.on('asynchronous-message', (event, arg) => {
  // 返回消息
  event.sender.send('asynchronous-reply', 'ok');
});

上面的代碼是異步監聽過程。 主進程設置好監聽,渲染進程經過ipcRenderer.send()發送消息。主進程得到消息後,經過event.sender.send()返回信息。返回信息也是異步的,因此渲染進程也設置了監聽。
另外,electron還提供了一種同步的消息傳遞方式。代碼以下:web

// renderer.js
console.log('synchronous-message: ', ipcRenderer.sendSync('synchronous-message', 'hello'));

// main.js
ipcMain.on('synchronous-message', (event, arg) => {
  event.returnValue = 'ok';
});

主進程與渲染進程相互傳遞數據的例子能夠去這裏獲取。chrome

調試

一個app的開發過程,會用到代碼調試,那麼electron應該如何進行調試呢?
electron中,渲染進程由於是Chromium的頁面,因此可使用DevTools進行調試。啓動DevTools的方式是:在main.js中,建立好BrowserWindow後,經過接口BrowserWindow.webContents.openDevTools();來打開頁面的DevTools調試工具,進行頁面調試,具體的調試方法和使用Chrome進行調試一致。
主進程是基於Node.js的,因此electron的調試和Node.js相似。這裏說下在VS Code中如何進行electron主進程的調試。
第一步,設置VS Code的tasks,用於啓動electron。相關配置以下:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "0.1.0",
  "command": "electron",
  "isShellCommand": true,
  "showOutput": "always",
  "suppressTaskName": true,
  "args": ["--debug=5858", "."]
}

其中,--debug=5858是用於調試Node.js的端口。
第二步,設置VS Code項目的調試配置。能夠生成launch.json,內容以下:

{
  "version": "0.2.0",
  "configurations": [ {
      "name": "Attach",
      "type": "node",
      "address": "localhost",
      "port": 5858,
      "request": "attach"
    }
  ]
}

其中的port:5858的端口信息須要和上面的--debug=5858端口保持一致。
配置完成後,即可以開始調試主進程。
首先啓動electron項目。
由於上面配置了task,因此可使用VS Code的task進行啓動。按下快捷鍵shift + command + p能夠啓動命令,輸入task electron命令,回車,就能夠運行electron的task進行項目的啓動。
項目啓動後,再開始設置主進程代碼的斷點。在VS Code的調試界面中設置斷點,並點擊運行。這個時候,操做啓動的electron應用,當運行到斷點所在代碼時,就能夠觸發斷點調試。

擴展功能

electron除了使用前端技術實現界面展現的功能外,還提供了大量的桌面環境接口。好比支持Notification,Jump List, dock menu等。具體支持哪些桌面接口以及如何使用,能夠去http://electron.atom.io/docs/... 瞭解。

打包

完成功能代碼後,咱們須要將代碼打成可運行的包。可使用electron-packager來進行應用打包,electron-packager支持windows, Mac, linux等系統。具體介紹能夠去https://github.com/electron-u... 瞭解。
打包的步驟很簡單,只須要兩步:

  1. 全局安裝Node.js模塊electron-packager

  2. 運行命令: electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]。 其中platform能夠取darwin, linux, mas, win324個值;arch能夠取ia32, x64兩個值。
    須要注意,打包後,代碼中的全部路徑都必須使用絕對路徑,經過${__dirname}得到app的根路徑,而後拼接成絕對路徑。

相關文章
相關標籤/搜索