Introduction
In this article, we'll learn to build cross-platform Desktop app for Angular 8/7 by integrating it with Electron.
Electron
Electron is an open-source framework developed and and maintained by GitHub. It is a popular platform for building cross-platform desktop apps for Windows, Linux and macOS with JavaScript, HTML, and CSS.It is essentially a web application that is self-contained as a desktop application.
In this guide, we will look at how to create an Electron application with the Angular framework using TypeScript. We will cover,
- Building a project from scratch
- Packaging the desktop application for distribution
- Using live reloading for development
Installing AngularCLI
Let’s get started by installing Angular CLI, which is the official tool for creating and working with Angular projects. Open a new terminal and run the below command.
npm install -g @angular/cli
Steps to follow,
Step 1
Create an Angular project setup using the below command or however you want to create it.
ng new projectname
Example,
ng new angularElectron
Step 2
Now, we must install Electron in our Angular app. Open a new terminal and run the below command.
npm install electron --save-dev
Even after installing, Electron will be unaware of the Angular app. So, it should be linked with the Angular app in order to work.
Step 3
Create a script file named as main.js and copy the below code in it. This file is used to link the Angular project with Electron.
- const {
- app,
- BrowserWindow
- } = require('electron')
-
-
- let win
-
- function createWindow() {
-
- win = new BrowserWindow({
- width: 800,
- height: 600,
- webPreferences: {
- nodeIntegration: true
- }
- })
-
- win.loadFile('dist/angularElectron/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()
- }
- })
- app.on('activate', () => {
-
-
- if (win === null) {
- createWindow()
- }
- })
-
-
Change the path of index.html in the script based on your project path.
Step 4
In Index.html, modify the below line
- <base href="/"> to <base href="./">
Refer line#6
Step 5
In package.json, add the below line to link the newly created script file.
"main":"main.js",
In Scripts, add the below code to run Electron with short code.
"electron":"ng build && electron ."
Step 6
Now, run the application
npm run electron
On successful execution of the above command, the following Angular UI window pops out.