Electronを使ってみる
開発環境は、Windows 10 Pro(64bit) + node v14.17.0 + npm 6.14.13。
1.公式サイトへアクセスし、ヘッダー部分のDocsをクリック
2.Quick Startのリンクをクリック
以下、Electron DocumentationのQuick Startに基づいて、やっていきたいと思います。
3.コマンドプロンプトを立ちあげてElectron用のディレクトリを作成する
※ここでディレクトリ名にelectronとすると、インストール時にエラーになるので、それ以外の名前をつけましょう。
cd c:\ && mkdir electron-app && cd electron-app
4.コマンドプロントでpackage.jsonを作成する
npm init -y
5.package.json内を修正
mainの欄は、index.jsからmain.jsに変更。
authorとdescriptionの欄は、空文字から、適当な文字を入力して変更。
scriptsの欄は、 "start": "electron ."を追加。
そして、以下のようにしました。
{ "name": "electron-app", "version": "1.0.0", "description": "Hello World", "main": "main.js", "scripts": { "start": "electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "koiken", "license": "ISC" }
6.コマンドプロンプトからElectronをインストールする
npm i -D electron
7.main.js、preload.js、index.htmlの3つのファイルを作成します。
main.js
const path = require('path') const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', function(){ if(BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Mac OS以外(Windows, Linux OS)だと、ウィンドウを消すと、バックグラウンドのプロセスも終了する app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() })
preload.js
window.addEventListener('DOMContentLoaded', () => { const replaceText = (selector, text) => { const element = document.getElementById(selector) if (element) element.innerText = text } for (const dependency of ['chrome', 'node', 'electron']) { replaceText(`${dependency}-version`, process.versions[dependency]) } })
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>. <script src="./renderer.js"></script> </body> </html>
7.コマンドプロンプト上で、以下のコマンドを入力
npm start
実行結果が下になります。ウィンドウが先に表示されて、時間差で、HTML部分が読み込まれます。