In this tutorial we’ll build a cross-platform desktop application with Electron and web technologies such as TypeScript and Angular.
Electron.js is a popular platform for building cross-platform desktop apps for Windows, Linux and macOS with JavaScript, HTML, and CSS. It’s created and maintained by GitHub and it’s available under the MIT permissive license. It was initially created for GitHub’s Atom editor, but has since been used to create applications by companies like Microsoft (Visual Studio Code), Facebook, Slack, and Docker.
Electron makes use of powerful platforms like Google Chromium and Node.js, but also provides its own set of rich APIs for interacting with the underlying operating system.
Electron provides a native container that wraps web apps so they look and feel like desktop apps with access to operating system features (similar to Cordova for mobile apps). This means we can use any JavaScript library or framework to build our application. In this tutorial, we’ll be using Angular.
Prerequisites
For this tutorial, you will need to have these prerequisites covered:
- Familiarity with TypeScript and Angular.
- Node.js and npm installed on your development machine.
Installing Angular CLI
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 following command:
npm install -g @angular/cli
We’ll install the Angular CLI globally on our system. If the command fails with the EACCESS error, add sudo
before your command in Linux or macOS, or run the command prompt as an administrator in Windows.
If the CLI is installed successfully, navigate to your working directory and create a new Angular project using the following commands:
cd ~
ng new electron-angular-demo
Wait for your project’s files to be generated and dependencies to be installed from npm. Next, navigate to the root of your project and run the following command to install the latest version of Electron from npm as a development dependency:
npm install --save-dev electron@latest
As of this writing, this command will install Electron v4.1.4.
Next, create a main.js
file and add the following code:
const {app, BrowserWindow} = require('electron')
const url = require("url");
const path = require("path");
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, `/dist/index.html`),
protocol: "file:",
slashes: true
})
);
// Open the DevTools.
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
if (mainWindow === null) createWindow()
})
This code simply creates a GUI window and loads the index.html
file that should be available under the dist
folder after we build our Angular application. This example code is adapted from the official starter repository.
Next, open the package.json
file of your project and add the main
key to set the main.js
file as the main entry point:
{
"name": "electron-angular-demo",
"version": "0.0.0",
"main": "main.js",
// [...]
}
Next, we need to add a script to easily start the Electron app after building the Angular project:
{
"name": "electron-angular-demo",
"version": "0.0.0",
"main": "main.js",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"start:electron": "ng build --base-href ./ && electron ."
},
// [...]
}
We added the start:electron
script which runs the ng build --base-href ./ && electron .
command:
- The
ng build --base-href ./
part of the command builds the Angular app and sets the base href to./
. - The
electron .
part of the command starts our Electron app from the current directory.
Now, in your terminal, run the following command:
npm run start:electron
An Electron GUI window will be opened, but will be blank. In the console, you’ll see the Not allowed to load local resource: /electron-angular-demo/dist/index.html error.
Electron is unable to load the file from the dist
folder because it simply doesn’t exist. If you look in your project’s folder, you’ll see that Angular CLI builds your app in the dist/electron-angular-demo
folder instead of just the dist
folder.
In our main.js
file, we are telling Electron to look for the index.html
file in the dist
folder without a subfolder:
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, `/dist/index.html`),
protocol: "file:",
slashes: true
})
);
__dirname
refers to the current folder from which we’re running Electron.
We use the path.join()
method to join the path of the current folder with the /dist/index.html
path.
You can either change the second part of the path to /dist/electron-angular-demo/index.html
or, better yet, change the Angular configuration to output the files in the dist
folder without using a subfolder.
Open the angular.json
file, locate the projects → architect → build → options → outputPath
key and change its value from dist/electron-angular-demo
to just dist
:
"projects": {
"electron-angular-demo": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
Head back to your terminal and again run the following command:
npm run start:electron
The script will call the ng build
command to build the Angular app in the dist
folder, and call electron
from the current folder to start the Electron window with the Angular app loaded.
This is a screenshot of our desktop app running Angular:
Calling Electron APIs from Angular
Let’s now see how we can call Electron APIs from Angular.
Electron apps make use of a main process running Node.js and a renderer process running the Chromium browser. We can’t directly access all of Electron’s APIs from the Angular app.
We need to make use of IPC or Inter-Process Communication, which is a mechanism provided by operating systems to allow communication between different processes.
Not all Electron APIs need to be accessed from the main process. Some APIs can be accessed from the renderer process, and some APIs can be accessed from both the main and renderer processes.
BrowserWindow, which is used to create and control browser windows, is only available in the main process. The desktopCapturer API (used for capturing audio and video from the desktop using the navigator.mediaDevices.getUserMedia
API) is only available in the renderer process. Meanwhile the clipboard API (for performing copy and paste operations on the system clipboard) is available on both the main and renderer processes.
You can see the complete list of APIs from the official docs.
Let’s see an example of calling the BrowserWindow
API, available only in the main process, from the Angular app.
Open the main.js
file and import ipcMain
:
const {app, BrowserWindow, ipcMain} = require('electron')
Next, define the openModal()
function:
function openModal(){
const { BrowserWindow } = require('electron');
let modal = new BrowserWindow({ parent: mainWindow, modal: true, show: false })
modal.loadURL('https://www.sitepoint.com')
modal.once('ready-to-show', () => {
modal.show()
})
}
This method will create a child modal window, load the https://www.sitepoint.com
URL inside it, and display it when it’s ready.
Next, listen for an openModal
message that will be sent from the renderer process and call the openModal()
function when the message is received:
ipcMain.on('openModal', (event, arg) => {
openModal()
})
Now, open the src/app/app.component.ts
file and add the following import:
import { IpcRenderer } from 'electron';
Next, define an ipc
variable and call require('electron').ipcRenderer
to import ipcRenderer
in your Angular component:
private ipc: IpcRenderer
constructor(){
if ((<any>window).require) {
try {
this.ipc = (<any>window).require('electron').ipcRenderer;
} catch (e) {
throw e;
}
} else {
console.warn('App not running inside Electron!');
}
}
The require()
method is injected at runtime in the renderer process by Electron and as such, it will only be available when running your web application in Electron.
Finally, add the following openModal()
method:
openModal(){
console.log("Open a modal");
this.ipc.send("openModal");
}
We use the send()
method of ipcRenderer
to send an openModal
message to the main process.
Open the src/app/app.component.html
file and add a button, then bind it to the openModal()
method:
<button (click)="openModal()">
Open Modal
</button>
Now, run your desktop app using the following command:
npm run start:electron
This is a screenshot of the main window with a button:
If you click on the Open Modal button, a modal window should be opened with the SitePoint website:
You can find the source code of this demo from this GitHub repository.
Conclusion
In this tutorial, we’ve looked at how to run a web application built with Angular as a desktop application using Electron. We hope you’ve learned how easy it can be to get started building desktop apps with your web development toolkit!
Frequently Asked Questions (FAQs) about Building a Desktop Application with Electron and Angular
How Can I Debug My Electron and Angular Application?
Debugging is an essential part of the development process. For Electron and Angular applications, you can use the Chrome Developer Tools. To open the developer tools, you can use the shortcut Ctrl+Shift+I or you can add a line of code in your main.js file: mainWindow.webContents.openDevTools()
. This will open the developer tools when your application starts. You can then inspect elements, view console logs, and debug your code just like you would in a web application.
How Can I Package My Electron and Angular Application for Distribution?
Packaging your Electron and Angular application for distribution can be done using electron-packager or electron-builder. These tools help you package your application into an executable file for different operating systems. You can customize the application’s name, description, version, and more. You need to install these packages as devDependencies and then add a script in your package.json file to run the packaging command.
Can I Use Angular Material with Electron?
Yes, you can use Angular Material with Electron. Angular Material is a UI component library that implements Material Design in Angular. It provides a wide range of pre-built components that you can use to create a user-friendly and responsive application. To use Angular Material, you need to install it using npm or yarn and then import the necessary modules in your application.
How Can I Handle File System Operations in Electron and Angular?
Electron provides a built-in module called fs (File System) that you can use to handle file system operations like reading and writing files. You can use it in the main process of your Electron application. However, if you want to use it in the renderer process (Angular), you need to use Electron’s IPC (Inter-Process Communication) to communicate between the main process and the renderer process.
How Can I Use Node.js Modules in My Electron and Angular Application?
Electron allows you to use Node.js modules in your application. You can use them in the main process directly. However, if you want to use them in the renderer process (Angular), you need to enable nodeIntegration in your Electron configuration. Be aware that enabling nodeIntegration can pose a security risk if your application loads remote content, so it’s recommended to use a more secure option like contextIsolation and preload scripts.
How Can I Update My Electron and Angular Application?
Updating your Electron and Angular application can be done using Electron’s autoUpdater module. This module allows you to automatically download and install updates in the background. You can also provide a user interface for the user to manually check for updates.
Can I Use Angular CLI with Electron?
Yes, you can use Angular CLI with Electron. Angular CLI is a command-line interface for Angular that helps you create, develop, and maintain Angular applications. You can use it to generate components, services, modules, and more. You can also use it to build your Angular application before running it with Electron.
How Can I Secure My Electron and Angular Application?
Securing your Electron and Angular application is crucial to protect your users’ data. Electron provides several security recommendations like enabling contextIsolation, disabling nodeIntegration, using sandbox mode, and more. You should also follow Angular’s security best practices like sanitizing user input, using the Https protocol, and more.
How Can I Test My Electron and Angular Application?
Testing your Electron and Angular application can be done using testing frameworks like Jasmine and Karma for Angular, and Spectron for Electron. These frameworks allow you to write unit tests and end-to-end tests to ensure that your application works as expected.
Can I Use Electron with Other Frameworks or Libraries?
Yes, Electron is framework-agnostic, which means you can use it with any JavaScript framework or library. Besides Angular, you can use it with React, Vue.js, Svelte, and more. You can also use it with vanilla JavaScript if you prefer.
Ahmed is a technical author and web developer living in Morocco with a Master's degree in software development. He authors technical content about JavaScript, Angular and Ionic. He is also a fan of entrepreneurship, poetry, and teaching. You can contact me on my personal website and read my other articles on Techiediaries.