Electron/インストール
提供: 初心者エンジニアの簡易メモ
インストール
公式:https://www.electronjs.org/ja/docs/latest/tutorial/quick-start
mkdir my-electron-app && cd my-electron-app npm init npm install --save-dev electron
package.json に"start": "electron ." を追加
{
"scripts": {
"start": "electron ."
}
}
空のindex.jsを追加
touch index.js
helloworldサンプル
index.js
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
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>
出力
Hello World! We are using Node.js , Chromium , and Electron .
サンプル(os別に適切に閉じる)
- windows,linuxでは、すべてのwindowを閉じると、アプリが閉じるように。
- macでは、すべてのwindowを閉じても、アプリは閉じないように。
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
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()
})
jsのモジュール化
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.js
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
出力
We are using Node.js 18.18.2, Chromium 120.0.6099.56, and Electron 28.0.0.
