Electron 简介及入门教程

Electron 是什么?

是使用 Web 技术构建跨平台的桌面应用程序的开源技术。Web 技术指的是 JavaScript、HTML 和 CSS 三驾马车。同时,这意味着,现在用于开发网站的主流技术,如 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 下载缓慢的问题,经过研究下载和 cache 部分的源代码,在 Mac 上的解决方案如下:

  1. 获取 zip 包的下载地址,根据上面的提示,作如下操作来获取下载地址
$ 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. 根据上面下载 url,建立目录 httpsgithub.comelectronelectronreleasesdownloadv10.1.0electron-v10.1.0-darwin-x64.zip

  4. 将下载好的文件 electron-v10.1.0-darwin-x64.zip 复制到该目录下,如下图所示:


    electron-cache.png
  5. 再次手工执行安装脚本

$ 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 / 安装 中的章节 “自定义镜像和缓存” 部分,有更好的方法!

  • 启动
$ npm start

启动的窗口如下:


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

代码实现简要分析

主要文件

  • 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

关键点已经写上中文注释。

// 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.
  // 创建主窗口
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 此处会自动加载和执行 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.
  // 打开开发者工具
  // 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])
  }
})

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341