LoginSignup
0
1

More than 1 year has passed since last update.

Electron - Hello World

Last updated at Posted at 2021-09-30

Electronでアプリを作ってみます。

※ 検証環境
Windows 10 Home, Node:v14.17.4, Electron:v15.0.0

プロジェクトの作成

まずNode.jsのプロジェクトを作ります。
entry pointは Electronアプリの慣例にならって main.js とします。

> npm init
...
package name: (...) プロジェクト名
version: (1.0.0)
description:
entry point: (index.js) main.js
test command:
git repository:
keywords:
author:
license: (ISC)
...

Electronをローカルインストールします。

npm i -D electron

アプリの実装

アプリのメインプロセスになる main.js を作成します。

main.js
const { app, BrowserWindow } = require('electron')

function createWindow () {
  // ウインドウ作成
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
  })

  // index.htmlの内容でウィンドウ表示
  mainWindow.loadFile('index.html')
}

// Electronの初期化完了時に呼ばれる
app.whenReady().then(() => {
  createWindow()

  // Mac用処理
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// (Mac以外は)ウインドウが全部閉じられたら終了
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

ウィンドウの描画内容となるindex.htmlを次の内容で作成します。

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

アプリの実行

コマンドラインで以下のように実行します。

node_modules\.bin\electron .

Hello World!とウィンドウに表示されれば成功です。

npm startで実行できるようにする

毎回electronのパスを打つのは面倒なので、npm start で起動できるようにしましょう。

package.json 内のscriptsにstartの定義を追加します。

package.json
  "scripts": {
   "start": "electron .",
   "test": "echo \"Error: no test specified\" && exit 1"
  }

すると、次からはコマンドラインで以下の通り実行すれば起動できるようになります。

npm start

参考

Electron Quick Start
https://www.electronjs.org/docs/tutorial/quick-start

0
1
4

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
1