Electron によるアプリ開発2020年9月20日 | |
はじめにElectron は、Web アプリ開発の技術を使ってデスクトップアプリを開発できるツールである。ここでは Electron によるアプリ開発の方法について記述する。 環境
Node.js が必要なので、別途用意しておく。 サンプルプロジェクトの作成プロジェクトのディレクトリを作成する。 $ mkdir example $ cd example 初期化。 $ npm init -y package.json が作成される。以下のような内容にする。
{
"name": "example",
"version": "0.1.0",
"main": "src/index.js",
"scripts": {
"start": "electron ."
}
}
Electron をインストール。 $ npm install --save-dev electron ソースコードを用意する。ソースコードを入れるディレクトリを作成する。 $ mkdir src メインのコードを以下のようにする。 src/index.js
const { app, BrowserWindow } = require("electron");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile("src/index.html");
}
app.whenReady().then(createWindow);
画面の HTML を用意。 src/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>.</p>
</body>
</html>
実行。 $ npm start ウインドウが表示され、バージョン情報が表示されれば OK。 デバッグツールメニュー [View]-[Toggle Developer Tools] で Chrome 同様のデバッグツールが表示される。 コードで開くこともできる。 mainWindow.webContents.openDevTools(); アプリ化アプリの形にするには、Electron Forge を使う。 改めてプロジェクトのディレクトリを作成する。 $ npx create-electron-app example-app src にソースコードを置く。 実行。 $ npm start アプリ化。 $ npm run make out ディレクトリができる。macOS の場合は、example-app-darwin-x64/example-app.app がバイナリになる (コマンドラインからだとディレクトリにしか見えないが)。Finder でこれをダブルクリックするとアプリが起動する。 アプリ化してもソースコードは丸見えなので注意 (example-app.app/Contents/Resources/app にある)。 ボタンを押して外部プログラムを実行する例最初のプロジェクトをコピーして新しいプロジェクトを作る。 $ cp example example2 $ cd example2 $ rm -r node_modules $ npm install child_process を使うので、インストールする。 $ npm install child_process index.js はそのまま。index.html を次のようにする。 index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>button</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<button id="button">Push!</button>
<pre id="view"></pre>
<script>
const { spawn } = require("child_process");
const button = document.getElementById("button");
button.onclick = () => {
spawn("ls", ["-l"]).stdout.on("data", data => {
const view = document.getElementById("view");
view.textContent = data;
});
}
</script>
</body>
</html>
参考 | |
| PENGUINITIS | |