「Electron」の版間の差分
ナビゲーションに移動
検索に移動
| 102行目: | 102行目: | ||
}) | }) | ||
</pre> | </pre> | ||
| + | ====package.json==== | ||
| + | ---- | ||
| + | <pre> | ||
| + | { | ||
| + | "name": "electron_sample", | ||
| + | "version": "1.0.0", | ||
| + | "main": "main.js", | ||
| + | "scripts": { | ||
| + | "start": "electron .", | ||
| + | }, | ||
| + | : | ||
| + | } | ||
| + | </pre> | ||
| + | *起動 | ||
| + | <pre> | ||
| + | npm start | ||
| + | </pre> | ||
| + | [[Fie:electron_sample_start.png|400px]] | ||
2021年5月4日 (火) 03:48時点における版
| Node.js | JavaScript | TypeScript | npm |
目次
Electron
Fiddle
Required
- Node.jsのインストール
基本的なアプリの作成
- Electronアプリケーションは本質的にNode.jsアプリケーション
- Electronアプリケーションは、package.json から開始される
プロジェクトの作成とElectronのインストール
mkdir my-electron-app && cd my-electron-app npm init -y npm i --save-dev electron
mainスクリプトファイル(main.js)の作成
- mainスクリプトは、Electronアプリケーションのエントリーポイント
- Mainプロセスを開始し、Mainプロセスはアプリケーションのライフサイクルをコントロールする
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
const win = new BrowserWindow({
width:400,
height:300,
webPreferences:{
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () =>{
if (BrowserWindow.getAllWindows().length == 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
Webページ(index.html)の作成
- index.html
- アプリケーション初期化時に一度だけ表示されるページ
- このページがレンダープロセスを表現する
<!DOCTYPE html>
<html>
<head>
<meta carhset="UTF-8">
<title>Electron Sample</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
<h2>Version</h2>
<div>
We are using Node.js <span id="node-version"></span>
</div>
<div>
Chromium <span id="chrome-version"></span>,
</div>
<div>
Electron <span id="electron-version"></span>.
</div>
</body>
</html>
プレロードスクリプト(preload.js)
- Node.jsとWebページのブリッジ
- Node.js全体を安全に公開するのではなく、特定のAPIや動作をWebページに公開することができる
- 以下ではprocessオブジェクトからバージョン情報を読み取りページを更新する
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) {
element.innerText = text;
}
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
package.json
{
"name": "electron_sample",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron .",
},
:
}
- 起動
npm start
© 2006 矢木浩人