Electron 簡介及入門教程

Electron 是什么?

是使用 Web 技術構建跨平臺的桌面應用程序的開源技術炼鞠。Web 技術指的是 JavaScript缘滥、HTML 和 CSS 三駕馬車。同時谒主,這意味著朝扼,現(xiàn)在用于開發(fā)網(wǎng)站的主流技術,如 Angular霎肯、Vue擎颖、React 等,均可以在 Electron 中應用观游。這也是一個將線上搬到線下的一個快捷的方式搂捧。

Electron 技術棧

Electron 特性

  • 自動更新
  • 原生菜單和通知
  • 崩潰報告
  • 調試和性能分析
  • Windows 安裝程序

簡單入門

  • 安裝 Node.js,建議使用 12.x 及以上
  • 啟動 Terminal(終端) / cmd
  • 進入一個臨時目錄
  • clone 入門示例工程
$ git clone https://github.com/electron/electron-quick-start
正克隆到 'electron-quick-start'...
remote: Enumerating objects: 15, done.
remote: Counting objects: 100% (15/15), done.
remote: Compressing objects: 100% (15/15), done.
remote: Total 686 (delta 6), reused 0 (delta 0), pack-reused 671
接收對象中: 100% (686/686), 445.88 KiB | 7.00 KiB/s, 完成.
處理 delta 中: 100% (360/360), 完成.
  • 安裝依賴庫
$ cd electron-quick-start
$ npm install

> core-js@3.6.5 postinstall /Users/arthur/temp/electron/electron-quick-start/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)


> electron@10.1.0 postinstall /Users/arthur/temp/electron/electron-quick-start/node_modules/electron
> node install.js

Downloading electron-v10.1.0-darwin-x64.zip: [====------------------------------------------------------------------------------------------------] 4% ETA: 18954.0 seconds

在安裝的時候懂缕,會碰到 electron 下載緩慢的問題允跑,經(jīng)過研究下載和 cache 部分的源代碼,在 Mac 上的解決方案如下:

  1. 獲取 zip 包的下載地址搪柑,根據(jù)上面的提示聋丝,作如下操作來獲取下載地址
$ cd /Users/arthur/temp/electron/electron-quick-start/node_modules/electron
$ DEBUG=* node install.js

筆者此刻獲取的下載地址是: https://github.com/electron/electron/releases/download/v10.1.0/electron-v10.1.0-darwin-x64.zip

  1. 手工下載 zip 包(此處各顯神通了)

  2. 轉到 electron 的 cache 目錄下(筆者是 /Users/arthur/Library/Caches/electron)

  3. 根據(jù)上面下載 url,建立目錄 httpsgithub.comelectronelectronreleasesdownloadv10.1.0electron-v10.1.0-darwin-x64.zip

  4. 將下載好的文件 electron-v10.1.0-darwin-x64.zip 復制到該目錄下工碾,如下圖所示:


    electron-cache.png
  5. 再次手工執(zhí)行安裝腳本

$ cd /Users/arthur/temp/electron/electron-quick-start/node_modules/electron
$ DEBUG=* node install.js
  ......
  extract-zip finished processing LICENSE +1ms
  extract-zip zip extraction complete +0ms
$
  1. 安裝成功弱睦!

!!! 更新: 參考官方文檔 Docs / Guides / 安裝 中的章節(jié) “自定義鏡像和緩存” 部分,有更好的方法倚喂!

  • 啟動
$ npm start

啟動的窗口如下:


electron-quick-start-window.png
  • 成功每篷!

代碼實現(xiàn)簡要分析

主要文件

  • index.html
  • main.js
  • package.json
  • preload.js
  • renderer.js

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

一個典型的 html 文件瓣戚,其中 node、chrome焦读、electron 的版本在 preload.js 中被替換子库。

main.js

關鍵點已經(jīng)寫上中文注釋。

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  // 創(chuàng)建主窗口
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 此處會自動加載和執(zhí)行 preload.js
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  // 加載主入口文件: index.html
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // 打開開發(fā)者工具
  // mainWindow.webContents.openDevTools()
}

// 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.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    // On macOS 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// 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.

preload.js

簡單的 DOM 操作矗晃,特別需要提到的是仑嗅,在這個時刻,可以訪問到 Node.js 的 API张症,如 process 對象仓技。

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市俗他,隨后出現(xiàn)的幾起案子脖捻,更是在濱河造成了極大的恐慌,老刑警劉巖兆衅,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件地沮,死亡現(xiàn)場離奇詭異,居然都是意外死亡羡亩,警方通過查閱死者的電腦和手機摩疑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來畏铆,“玉大人雷袋,你說我怎么就攤上這事〈蔷樱” “怎么了楷怒?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長瓦灶。 經(jīng)常有香客問我率寡,道長,這世上最難降的妖魔是什么倚搬? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮乾蛤,結果婚禮上每界,老公的妹妹穿的比我還像新娘。我一直安慰自己家卖,他們只是感情好眨层,可當我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著上荡,像睡著了一般趴樱。 火紅的嫁衣襯著肌膚如雪馒闷。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天叁征,我揣著相機與錄音纳账,去河邊找鬼。 笑死捺疼,一個胖子當著我的面吹牛疏虫,可吹牛的內容都是我干的。 我是一名探鬼主播啤呼,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼卧秘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了官扣?” 一聲冷哼從身側響起翅敌,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎惕蹄,沒想到半個月后蚯涮,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡焊唬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年恋昼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赶促。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡液肌,死狀恐怖,靈堂內的尸體忽然破棺而出鸥滨,到底是詐尸還是另有隱情嗦哆,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布婿滓,位于F島的核電站老速,受9級特大地震影響,放射性物質發(fā)生泄漏凸主。R本人自食惡果不足惜橘券,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望卿吐。 院中可真熱鬧旁舰,春花似錦、人聲如沸嗡官。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽衍腥。三九已至磺樱,卻和暖如春纳猫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背竹捉。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工芜辕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人活孩。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓物遇,卻偏偏與公主長得像,于是被迫代替她去往敵國和親憾儒。 傳聞我的和親對象是個殘疾皇子询兴,可洞房花燭夜當晚...
    茶點故事閱讀 44,779評論 2 354