LoginSignup
40

More than 5 years have passed since last update.

Electron + Express.js のミニマム構成の Web アプリを作る

Last updated at Posted at 2016-03-31

ElectronExpress.js を使ってローカルで HTTP サーバを動かして、.dmg ディスクイメージで配布可能な Mac 用の Web ベースのデスクトップアプリを、ミニマム構成で作成してみます。


こんな用途がターゲットです:

  • Node.js / Express.js ベースの Web サーバアプリを作っている
  • Browserify とかを使った Web クライアントアプリを作っている
  • EC2 とかの外部サーバを使わずに、ローカルの Mac 上で動くデスクトップアプリとして配布してみたい

こんな用途はターゲットではありません:

  • Electron の詳しい仕組みを知りたい場合
  • Atom みたいな本格的なデスクトップアプリを作りたい場合
  • Windows でも動くマルチプラットフォームなアプリを作りたい場合

(1)フォルダを作る

$ mkdir hello
$ cd hello

(2)最低限の package.json を書く

package.json
{
  "name": "hello",
  "version": "1.0.0",
  "build": {
    "app-bundle-id": "com.example.hello",
    "app-category-type": "public.app-category.utilities"
  },
  "main": "main.js"
}

(3)最低限のウェブコンテンツを置いておく

$ mkdir public
$ echo 'Hello, Electron!' > public/index.html

※ 本当は public フォルダに Web クライアントアプリを置く。

(4)最低限の main.js を書く

main.js
var electron = require("electron");
var express = require("express");
var exapp = express();
exapp.use(express.static("public"));
exapp.listen(3000, "127.0.0.1");
electron.app.on("ready", function () {
  var main = new electron.BrowserWindow({width: 800, height: 600});
  main.on("closed", electron.app.quit);
  main.webContents.openDevTools();
  main.loadURL("http://127.0.0.1:3000/");
});

※ 本当は express アプリの API サーバとかを実装する。
※ 本当は 3000 番ポート固定ではない方が良さそう。

(5)最低限に必要なモジュールをインストールする

npm install --save express
npm install --save-dev electron-prebuilt
npm install --save-dev electron-packager 

(6)とりあえず実行してみる

./node_modules/.bin/electron main.js 

Electron

(7).app が入った .dmg のディスクイメージを作成する

./node_modules/.bin/electron-packager . --platform=darwin --arch=x64 --ignore=src --out=dist
hdiutil create -srcfolder dist/hello-darwin-x64/hello.app dist/hello.dmg

※ 配布しないソースコードのディレクトリを --ignore で指定できる。

(8)ディスクイメージを開いてみる

open dist/hello.dmg 
open /Volumes/hello

hello.dmg

(9)アプリができました!

アプリの中身は以下のようなファイル構成でした。

/Volumes/hello/hello.app/Contents/Resources/app/app/index.js
/Volumes/hello/hello.app/Contents/Resources/app/app/server.js
/Volumes/hello/hello.app/Contents/Resources/app/main.js
/Volumes/hello/hello.app/Contents/Resources/app/node_modules/express/History.md
/Volumes/hello/hello.app/Contents/Resources/app/node_modules/express/index.js
/Volumes/hello/hello.app/Contents/Resources/app/node_modules/express/LICENSE
/Volumes/hello/hello.app/Contents/Resources/app/node_modules/express/package.json
/Volumes/hello/hello.app/Contents/Resources/app/node_modules/express/Readme.md
/Volumes/hello/hello.app/Contents/Resources/app/package.json
/Volumes/hello/hello.app/Contents/Resources/app/public/index.html

初めて Electron を使ってみたので、間違っているところがあったら教えて下さい。

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
40