Web

Electron with Angular

Posted by Kerwen Blog on February 26, 2020

If you have already have a web application(eg. Agnualr), this is how to integrate web application with Electron.

Create new Angular project

  1. Create new folder “Angular” and open with VSCode
  2. Open new terminal in VSCode and install the latest version of the Angular CLI globally:

    1
    
    npm i -g @angular/cli
    
  3. Navigate to your work folder and let’s create our new Angular app, called my-app:

    1
    2
    
    ng new my-app
    cd my-app
    
  4. Run following command to start web service

    1
    
    npm start
    
  5. Open web browser and input http://localhost:4200/
    image

Integrate with Electron

  1. Install latest electron

    1
    
    npm i -D electron@latest
    

Note: It may take 10+ minutes to install electron, depends on network performance.

  1. Create new main.js file under my-app folder. This file will be the entry point for our Electron app and will contain the main API for the desktop app

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    
    const {app, BrowserWindow} =require("electron")
    const path = require("path")
    const url = require("url")
    
    let win;
    
    function CreateWindow(){
        win = new BrowserWindow({
            width: 800,
            height: 600
        })
    
        win.loadURL(
            url.format({
                pathname: path.join(__dirname, '/dist/index.html'),
                protocol: "file",
                slashes: true
            })
        )
    
        win.setMenu(null)
    
        win.on("close", () => {
            win = null
        })
    }
    
    app.on("ready", CreateWindow);
    
    app.on("window-all-closed", () => {
        if(process.platform !== "darwin"){
            app.quit();
        }
    })
    
    app.on("activate", ()=> {
        if(win === null){
            CreateWindow();
        }
    })
    
  2. Modify package.json file, add electron main entry

    1
    2
    3
    
    "name": "my-app",
    "version": "0.0.0",
    "main": "main.js",
    
  3. Add new scripts

    1
    2
    
    "scripts": {
        "electron": "ng build --base-href ./ && electron .",
    
  4. Modify angular.json file

    1
    2
    3
    4
    5
    
    "architect": {
            "build": {
            "builder": "@angular-devkit/build-angular:browser",
            "options": {
                "outputPath": "dist",
    
  5. Running app

    1
    
    Npm run electron  ![image](https://github.com/kerwenzhang/kerwenzhang.github.io/blob/master/_posts/image/electron2.png?raw=true)
    

reference