Electron 入門教學

講者:土豆

時間:2020/03/21

大綱

  • Electron簡介
  • 製作 clipboard 小程式
  • 所以,我應該用 electron嗎?

Electron 簡介

什麼是 Electron

  • 圖形介面桌面程式開發框架
  • 可使用前端技術(JavaScript, HTML, CSS)開發
  • Vue, React, Angular, Bootstrap, jQuery 都可以使用歐

Atwood's Law

Any application that cat be written in JavaScript, will eventually be written in JavaScript.

(Stack Overflow 創辦人)

為什麼要用 Electron?

  • 會寫前端就會用
  • 可以用你最喜歡(或討厭)的前端技術
  • 跨平台(Windows, MacOS, Linux)

為什麼不要用 Electron?

  • 相較於原生語言較為緩慢
  • 打包了一個chromium,即便是很簡單的小程式也有一定的檔案大小
  • 資源消耗較多
  • 並不是真的只需要一份 code 就可以跨平台

使用 Electron 製作的軟體

  • Atom
  • Visual Studio Code
  • Slack
  • Discord
  • ......

製作 clipboard 小程式

目標

  • 自動記錄複製過的文字
  • 隨時可以重新複製回來

建立環境

npx create-electron-app electron_clipboard

npx:使用完即刪除,不佔空間

npm install -g create-electron-app # 可能需要加sudo
npx create-electron-app electron_clipboard

如果上面指令不行,試試下面的

需要先裝好 node 以及 git

index.js

const { app, BrowserWindow } = require('electron');
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // 加入下面三行開啟在browser端import module的功能
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, '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.on('ready', 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', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // 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 (BrowserWindow.getAllWindows().length === 0) {
    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 import them here.

請修改成以下程式碼

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <link rel="stylesheet" href="index.css">

    <script defer src="render.js"></script>
  </head>
  <body>
    <h1>剪貼簿</h1>
    <button id="pasteBtn" class="btn btn-primary">貼入剪貼簿</button>
    <div id="textList"></div>
  </body>
</html>

請修改成以下html

render.js

const { clipboard } = require('electron');

const textList = document.getElementById('textList');
const pasteBtn = document.getElementById('pasteBtn');
let itemId = 0;

function copyTextToClipboard(itemId) {
    let text = document.getElementById(itemId).getElementsByTagName('span')[0].textContent;
    clipboard.writeText(text);
}

function removeTextFromPage(itemId) {
    document.getElementById(itemId).remove();
}

function pastCliboarTextToPage() {
    let textFromClipboard = clipboard.readText();
    textList.innerHTML += '<div id="' + itemId + '"class="m-3"><span class="mx-2">' + 
                          textFromClipboard + 
                          '</span><button class="btn btn-sm btn-success" onclick="copyTextToClipboard(' + itemId + ')">複製</button>' + 
                          '<button class="btn btn-sm btn-danger" onclick="removeTextFromPage(' + itemId + ')">刪除</button>' +
                          '</div>';
    itemId += 1;
}

pasteBtn.addEventListener('click', () => {
    pastCliboarTextToPage();
});

請新增檔案並新增以下程式碼

所以,我應該用 electron嗎?

  • 受限於Chromium,人家沒做的就不能用(e.g. clipboard listener)
  • 新技術,文件有點少
  • 檔案太大

但是...

  • 你可以叫前端工程師寫桌面程式!(人力costdown,money up up up)
  • 寫起來蠻有趣的
  • 專案持續開發維護中(只要vscode不倒,就不會倒)

所以...就看你個人考量

  • 團隊成員熟悉前端技術?
  • 開發時間?
  • Electron做得到你想做的事?

參考資料

Made with Slides.com