1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angular + Electron事始め

Posted at

Angular + Electron事始め

概要

Electronが気になっていた今日このごろ。
Angularを久しぶりに触りたいこともあり、Angular + Electronでアプリを作ってみようと思う。
とりあえずAngular-CLIで作ったテンプレートをElectron使って起動できるところまですすめていく。

TL;DR.

ソースコード

手順

Angularプロジェクト作成

# いつも通りCLIからスタート
$ng new angular-electron

Electronインストール

$ npm install electron --save-dev

起動できるように各種修正

公式ドキュメントangular-electronを参考に作っていく。

Angular.jsonを修正

projects > architect > build > oprions > outputPath/dist/プロジェクト名(今回はangular-electron)distのみに修正。

{
  ...
  "projects": {
    ...
      "architect": {
        "build": {
          ...
          "options": {
            "outputPath": "dist",
            ...

main.jsを作成

アプリを起動するためのjsを作成する。
tsで書きたかったりホットリロードとかも試したいところだけど、
一旦jsでちゃんと動くところまで確認する。

const { app, BrowserWindow, screen } = require('electron');
const url = require('url');
const path = require('path');

let win = null;

function createWindow() {
  const electronScreen = screen;
  const size = electronScreen.getPrimaryDisplay().workAreaSize;

  // ブラウザウインドウを作成
  win = new BrowserWindow({
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadURL(url.format({
    pathname: path.join(__dirname, 'dist/index.html'),
    protocol: 'file:',
    slashes: true
  }));

  // dev toolを開く
  win.webContents.openDevTools();

  win.on('closed', () => win = null);

  return win;
};

app.allowRendererProcessReuse = true;

app.on('ready', () => setTimeout(createWindow, 400));
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});

package.jsonを修正

electronコマンドで起動できるようにpackage.jsonmainに上記ファイルを指定する。

{
	"name": "angular-electron",
	"main": "main.js",
	...
}

起動できることを確認する

アプリを起動できることを確認する。
その前にAngularのビルドが必要なので実行しておく。

# Angularのファイルをビルド(最初から入っているコマンドそのまま)
$ npm run build
> dist配下にファイルが出力されていることを確認

# アプリを起動してみる
$ npx electron .

画像のようにAngular-CLIのテンプレートが表示されることを確認できればOK。
image.png

まとめ

Electron + Angularでアプリを作ってみようと思ったので、とりあえず起動できるまでやった。
起動だけならさっくりできたので、次はmain.jsをts化したり、アプリを作っていきたいところ。

参考サイト

1
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?