当記事の目的
Electron(デスクトップアプリ)のサンプルを作成。
NodeJSがインストールされていることを確認。
> node -v
v12.16.2
プロジェクト用packege.json作成
> npm init
###electronパッケージをインストール
> npm i -D electron
各種ファイル作成
srcフォルダを作成し、その配下にアプリ用ファイルを作成する。
・アプリ用packege.json作成
package.json
{"main":"main.js"}
main.js
// アプリケーション作成用のモジュールを読み込みconst{app,BrowserWindow}=require('electron');// メインウィンドウletmainWindow;functioncreateWindow(){// メインウィンドウを作成mainWindow=newBrowserWindow({webPreferences:{nodeIntegration:true,},width:800,height:600,});// メインウィンドウに表示するURLを指定// (今回はmain.jsと同じディレクトリのindex.html)mainWindow.loadFile('index.html');// デベロッパーツールの起動mainWindow.webContents.openDevTools();// メインウィンドウが閉じられたときの処理mainWindow.on('closed',()=>{mainWindow=null;});}// 初期化が完了した時の処理app.on('ready',createWindow);// 全てのウィンドウが閉じたときの処理app.on('window-all-closed',()=>{// macOSのとき以外はアプリケーションを終了させますif(process.platform!=='darwin'){app.quit();}});// アプリケーションがアクティブになった時の処理(Macだと、Dockがクリックされた時)app.on('activate',()=>{// メインウィンドウが消えている場合は再度メインウィンドウを作成するif(mainWindow===null){createWindow();}});
index.html
<html><head><metacharset="UTF-8"><title>Hello World!</title></head><body><h1>初めてのElectron</h1>
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>.
</body></html>
起動
> npx electron ./src
パッケージング
> npm i -D electron-packager
・Windows
> npx electron-packager src SampleApp --platform=win32 --arch=x64 --overwrite
・macOS(darwin)
> npx electron-packager src SampleApp --platform=darwin --arch=x64 --overwrite