0
2

More than 3 years have passed since last update.

【NodeJS】Electron(デスクトップアプリ)入門

Posted at

当記事の目的

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');

// メインウィンドウ
let mainWindow;

function createWindow() {
  // メインウィンドウを作成
  mainWindow = new BrowserWindow({
    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>
  <meta charset="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

サンプル画面.png

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2