Electron(0) - Hello world

Electron in Action 這本書寫得很不錯,無奈 electron 這個套件更新神速所以書中有些程式碼需要修正。這個系列紀錄 Electron in Action 中的修正供大家參考。

1. 創建專案:

使用npm初始化專案並下載套件:

$ mkdir PROJECT_NAME
$ cd PROJECT_NAME
$ npm init
$ npm install --save-dev electron

2. 專案架構:

Electron in Action 中會將專案所需之程式碼放在 '專案/app/' 中:

app
├── app.js
├── index.html
├── preload.js
├── renderer.js
└── style.css

其中 renderer.js 在這篇還不會用到。


3. app.js:

app.js 控制整個 app 的 life cycle,啟動 app 時我們會呼叫 preload.js 取得額外資訊。

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

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        } 
    });

    win.loadFile('./app/index.html');
}

app.whenReady().then(() => {
    createWindow();
});

4. preload.js:

preload.js 可以使用網頁(e.g. window)及 electron 的物件(e.g. process)。

window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector) => {
        const elementId = `${selector}-version`
        const element = document.getElementById(elementId);
        console.log(element);
        if (element) {
            const version = process.versions[selector];
            console.log(`${selector}: {version}`);
            element.innerText = version;
        }
    };

    for (const type of ['node', 'chrome', 'electron']) {
        replaceText(type);
    }
});

preload.js 中定義了 'DOMContentLoaded' 的 callback,等到 DOM load 完時會依照 ID 選取特定的 elements 並進行更新。


5. index.html:

在 app.js 中我們有將主頁面設為 index.html,詳細內容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <h1>Hello world</h1>
    <p>We are using node: <span id="node-version"></span></p>
    <p>We are using chrome: <span id="chrome-version"></span></p>
    <p>We are using electron: <span id="electron-version"></span></p>
</body>
</html>

6. package.json:

因應 app/ 的架構修改入口函數的名稱並新增 start 指令。

{
  "name": "electronplayground",
  "version": "1.0.0",
  "description": "",
  "main": "./app/app.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^16.0.7"
  }
}

執行 'npm start' 啟動應用:


留言

熱門文章