Electronを試す【今更感】
Electron
簡単にいうとhtmlとかでデスクトップアプリを作成できるものらしい 基本Webアプリのことをメインにやってきてデスクトップアプリ開発とかやってないが 自分がなんかで使えそうなツールを開発するのに利用できそうと思いチュートリアルをやってみる
環境
Mac node14.20.0(nodenv)
クイックスタート
ディレクトリ作成
アプリ用のディレクトリを準備
mkdir electron-samples && cd electron-samples mkdir app1 && cd app1 yarn init --private -y
パッケージ追加
electronを追加
yarn add --dev electron
関連コード
今回はチュートリアルのため、既存コードをそのまま添付
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'"> <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>. </body> </html>
index.js
// アプリケーションの寿命の制御と、ネイティブなブラウザウインドウを作成するモジュール const { app, BrowserWindow } = require("electron"); const path = require("path"); const createWindow = () => { // ブラウザウインドウを作成します。 const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, "preload.js"), }, }); // そしてアプリの index.html を読み込みます。 mainWindow.loadFile("index.html"); // デベロッパー ツールを開きます。 // mainWindow.webContents.openDevTools() }; // このメソッドは、Electron の初期化が完了し、 // ブラウザウインドウの作成準備ができたときに呼ばれます。 // 一部のAPIはこのイベントが発生した後にのみ利用できます。 app.whenReady().then(() => { createWindow(); app.on("activate", () => { // macOS では、Dock アイコンのクリック時に他に開いているウインドウがない // 場合、アプリのウインドウを再作成するのが一般的です。 if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); // macOS を除き、全ウインドウが閉じられたときに終了します。 ユーザーが // Cmd + Q で明示的に終了するまで、アプリケーションとそのメニューバーを // アクティブにするのが一般的です。 app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });
preload.js
// All the Node.js APIs are available in the preload process. // Chrome 拡張機能と同じサンドボックスも持っています。 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]); } });
ビルド用パッケージも追加
yarn add --dev @electron-forge/cli npx electron-forge import
実行
ひとまずはここまで