LoginSignup
1
2

More than 3 years have passed since last update.

Angular を Electron で動かす

Last updated at Posted at 2020-03-31

Angular を Electron で動かす際の導入方法は色々と記事があるけど、環境やらバージョンの問題で手順が微妙に違って地味につまづいたのでメモ。

ちなみに最終的にたどり着きたいのは Angular のイベントで Electron からローカルファイルの呼び出しというブラウザの越えられない壁を越えるのが目標。

環境

OS: mac OS Catalina 10.15.4
Angular CLI: 9.1.0
Node: 13.12.0

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.0
@angular-devkit/core         9.1.0
@angular-devkit/schematics   9.1.0
@schematics/angular          9.1.0
@schematics/update           0.901.0
rxjs                         6.5.4

構築手順

Angular プロジェクトの作成

ng new sample1

で普通に作成。
作成直後に /sample1/src/app/app.component.ts を開くと、linter が error 吐いて来るので、気になる場合は、手の甲を裏返しにしにて「なんでやん」と滑舌良く発音しながら空中でビシッとした後、下のように修正しておく。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html',
})
export class AppComponent {
  public title = 'sample1';
}

Electron の追加

cd sample1
npm install --save-dev electron@latest

で追加(この記事作成時点での latest は 8.2.0)。追加時に npm が

found 2 low severity vulnerabilities
run npm audit fix to fix them, or npm audit for details

と言ってきたけど実行しても

2 vulnerabilities required manual review and could not be updated

と言われるのでそのままに。

Electron 用の実行 js 追加

sample1 直下に main.js を追加。

const { app, BrowserWindow } = require('electron');
let win;

function createWindow() {

  // ウインドウの作成
  win = new BrowserWindow({
    width: 800
    , height: 400
    , webPreferences: {
      nodeIntegration: true
    }
  })

  // ウインドウに表示する内容
  win.loadFile('dist/sample1/index.html');

  // デバッグ画面表示
  win.webContents.openDevTools();

  // このウインドウが閉じられたときの処理
  win.on('closed', () => {
    win = null;
  })
}

// アプリが初期化されたとき(起動されたとき)
app.on('ready', () => {
  createWindow();
})

// 全ウインドウが閉じられたとき
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
})

// アクティブになったとき(MacだとDockがクリックされたとき)
app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
})

package.json に Electron 用の実行 js 追加

{
  "name": "sample1",
  "version": "0.0.0",
  "main": "main.js",
  ≈ 省略 ≈

package.json に Electron 用のビルドコマンド追加

≈ 省略 ≈
"scripts": {
  ≈ 省略 ≈
  "start:electron": "ng build --base-href ./ && electron ."
},
≈ 省略 ≈

実行

npm run start:electron

で起動。

electron1.png

次はイベント制御を行う。

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