Integrating Electron with Angular

ElectronJS

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.

Integration with Angular

First, we add Electron into the project by use of the command:

npm i -D electron@latest

Then, we will need to create an electron.dev.js file under the src folder and insert the following code:

const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");
​
let win;
const createWindow = () => {
​
  setTimeout(() => {
​
    win = new BrowserWindow({
      width: 800,
      height: 600,
      icon: "./src/favicon.ico",
    });
​
    win.loadURL(
      url.format({
        pathname: "localhost:4200",
        protocol: "http:",
        slashes: true,
      })
    );
​
    win.webContents.openDevTools();

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

As a next step, we have to adjust some scripts in our package.json. For that we need to install the concurrently package:

npm install concurrently --save-dev

Then we add a script that runs Electron:

"electron": "electron ./src/electron.dev"

… and change the start script to:

"start": "concurrently \"ng serve\" \"npm run electron\""

Lastly, add:

main”: "electron.dev.js",

The concurrently module allows us to run the ng serve command and the electron script simultaneously.

We can now run npm start in a terminal and the window will be opened with the loaded Angular application in it.