search
HomeWeb Front-endJS TutorialBuild a Desktop Application with Electron and Angular

Build a Desktop Application with Electron and Angular

Build cross-platform desktop applications: the perfect combination of Electron and Angular

This tutorial demonstrates how to build cross-platform desktop applications using Electron and Angular. Electron.js is a popular platform for creating desktop applications for Windows, Linux, and macOS using JavaScript, HTML, and CSS. It leverages powerful platforms such as Google Chromium and Node.js and provides its own set of APIs for interacting with the operating system.

We will learn how to install the Angular CLI, create a new Angular project, and install the latest version of Electron from npm as a development dependency. The tutorial also includes creating a GUI window and loading the index.html file, setting the main.js file as the main entry point, and adding a script to start the Electron application after building the Angular project.

In addition, we will learn how to call the Electron API from Angular using IPC (Interprocess Communication), which allows communication between different processes. We will demonstrate how to call the BrowserWindow API from an Angular application, and how to create a submodal window where the URL is loaded and display it when ready.

Electron's Advantages

Electron uses powerful platforms such as Google Chromium and Node.js, while providing rich APIs to interact with the underlying operating system. It provides a native container to encapsulate web applications, making them look and feel like desktop applications, and have access to operating system features (similar to Cordova for mobile applications). This means we can use any JavaScript library or framework to build our applications. In this tutorial, we will use Angular.

Precautions

This tutorial needs to meet the following prerequisites:

  • Familiar with TypeScript and Angular.
  • Install Node.js and npm on the development machine.

Installation of Angular CLI

First, install the Angular CLI, the official tool for creating and using Angular projects. Open a new terminal and run the following command:

npm install -g @angular/cli

We will install the Angular CLI globally. If the command fails due to an EACCESS error, add sudo before the command in Linux or macOS, or run a 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 command:

cd ~
ng new electron-angular-demo

Waiting for project file generation and dependencies to be installed from npm. Next, navigate to the project's root directory 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.

Create main.js file

Next, create a main.js file and add the following code:

npm install -g @angular/cli

This code simply creates a GUI window and loads the index.html file (which should be available in the dist folder after the Angular application is built). This sample code is adapted from the official introductory repository.

Configuration package.json

Next, open the project's package.json file and add the main key to set the main.js file as the main entry point:

cd ~
ng new electron-angular-demo

Add a startup script

Next, we need to add a script to easily start the Electron application after building the Angular project:

npm install --save-dev electron@latest

We added the start:electron script, which runs ng build --base-href ./ && electron . Command:

    The ng build --base-href ./ part of the
  • command builds the Angular application and sets base href to ./.
  • The
  • command's electron . section starts our Electron application from the current directory.

Now, in your terminal, run the following command:

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
    })
  );
  // 打开开发者工具
  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()
})

will open an Electron GUI window, but it will be blank. In the console, you will see the "Loading local resources: /electron-angular-demo/dist/index.html" error.

Electron cannot load the file from the dist folder because it does not exist at all. If you look at the folder of your project, you will see that the Angular CLI builds your application in the dist/electron-angular-demo folder, not the dist folder.

In our main.js file, we tell Electron to find the index.html file in the dist folder without subfolders:

{
  "name": "electron-angular-demo",
  "version": "0.0.0",
  "main": "main.js",
  // [...]
}

__dirname refers to the current folder where we run Electron.

We use the path.join() method to connect the path of the current folder with the /dist/index.html path.

You can change the second part of the path to /dist/electron-angular-demo/index.html, or better yet, change the Angular configuration to output files in the dist folder without using subfolders .

Open the angular.json file, find the projects → architect → build → options → outputPath key and change its value from dist/electron-angular-demo to dist:

{
  "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 ."
  },
  // [...]
}

Go back to your terminal and run the following command again:

npm run start:electron

The script calls the ng build command to build the Angular application in the dist folder and calls electron from the current folder to start the Electron window loading the Angular application.

This is a screenshot of our desktop application running Angular:

Build a Desktop Application with Electron and Angular

(The following is consistent with the original text, but the paragraphs and titles have been adjusted to make them easier to read and understand.)

Calling the Electron API from Angular

Now let's see how to call the Electron API from Angular.

The Electron application uses the main process running Node.js and the renderer process running the Chromium browser. We cannot access all Electron's APIs directly from the Angular application.

We need to use IPC or inter-process communication, which is a mechanism provided by the operating system 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 the main process and the renderer process.

BrowserWindow (used to create and control browser windows) is only available in the main process. desktopCapturer API (for capturing audio and video from desktop using 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 in both the main process and the renderer process.

You can view the complete list of APIs from the official documentation.

Let's look at an example of calling the BrowserWindow API from an Angular application (available only in the main process).

Open the main.js file and import ipcMain:

npm install -g @angular/cli

Next, define the openModal() function:

cd ~
ng new electron-angular-demo

This method will create a submodal window where the https://www.php.cn/link/aeda4e5a3a22f1e1b0cfe7a8191fb21a URL is loaded and display it when it is ready.

Next, listen for openModal message sent from the renderer process and call the openModal() function when the message is received:

npm install --save-dev electron@latest

Now, open the src/app/app.component.ts file and add the following import:

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
    })
  );
  // 打开开发者工具
  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()
})

Next, define an ipc variable and call require('electron').ipcRenderer to import ipcRenderer in your Angular component:

{
  "name": "electron-angular-demo",
  "version": "0.0.0",
  "main": "main.js",
  // [...]
}
The

require() method is injected by Electron into the renderer process at runtime, so it is only available when running a web application in Electron.

Finally, add the following openModal() method:

{
  "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 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, and bind it to the openModal() method:

npm run start:electron

Now, run your desktop application with the following command:

mainWindow.loadURL(
  url.format({
    pathname: path.join(__dirname, `/dist/index.html`),
    protocol: "file:",
    slashes: true
  })
);

This is a screenshot of the main window with buttons:

Build a Desktop Application with Electron and Angular

If you click the "Open Modal" button, a modal window with the SitePoint website should open:

Build a Desktop Application with Electron and Angular

You can find the source code for this demo from this GitHub repository.

Conclusion

In this tutorial, we looked at how to run a web application built using Angular as a desktop application using Electron. We hope you have learned how easy it is to start building desktop applications with the Web Development Kit!

(The following content is the original FAQs part, and it is slightly adjusted to make it more in line with the Chinese expression habits.)

FAQs (FAQs)

How to debug Electron and Angular applications?

Debugging is an important part of the development process. For Electron and Angular applications, you can use Chrome Developer Tools. To open the developer tool, you can use the shortcut key Ctrl Shift I, or you can add a line of code to the main.js file: mainWindow.webContents.openDevTools(). This will open the developer tools when the application starts. You can then check elements, view console logs, and debug code just like you would in your web application.

How to package Electron and Angular applications for distribution?

Electron and Angular applications can be packaged for distribution using electron-packager or electron-builder. These tools help you package your applications into executable files for different operating systems. You can customize the name, description, version, and more of the application. You need to install these packages as devDependencies and then add a script in the package.json file to run the package command.

Can you use Angular Material in Electron?

Yes. Angular Material is a UI component library that implements Material Design in Angular. It offers a variety of pre-built components that you can use to create user-friendly and responsive applications. To use Angular Material, you need to install it using npm or yarn and then import the necessary modules in the application.

How to 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 such as reading and writing files. You can use it in the main process of the Electron application. However, if you want to use it in a renderer process (Angular), you need to use Electron's IPC (Inter-process Communication) to communicate between the main process and the renderer process.

How to use the Node.js module in Electron and Angular applications?

Electron allows you to use the Node.js module in your application. You can use them directly in the main process. However, if you want to use them in the renderer process (Angular), you need to enable nodeIntegration in your Electron configuration. Note that enabling nodeIntegration poses a security risk if your application loads remote content, so it is recommended to use safer options such as contextIsolation and preload scripts.

How to update Electron and Angular applications?

Electron and Angular applications can be updated 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 users to manually check for updates.

Can you use Angular CLI with Electron?

Yes. Angular CLI is Angular's command-line interface 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 Angular applications before running with Electron.

How to protect the security of Electron and Angular applications?

Protecting the security of Electron and Angular applications is essential to protecting user data. Electron provides some security suggestions, such as enabling contextIsolation, disabling nodeIntegration, using sandbox mode, and more. You should also follow Angular security best practices such as cleaning up user input, using the Https protocol, and more.

How to test Electron and Angular applications?

You can use testing frameworks such as Jasmine and Karma (for Angular) and Spectron (for Electron) to test Electron and Angular applications. These frameworks allow you to write unit tests and end-to-end tests to ensure that your application works as expected.

Can Electron be used with other frameworks or libraries?

Yes. Electron is not about frameworks, which means you can use it with any JavaScript framework or library. In addition to Angular, you can also use it with React, Vue.js, Svelte and more. You can also use it with native JavaScript if you prefer.

The above is the detailed content of Build a Desktop Application with Electron and Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.