Home Web Front-end JS Tutorial Build a Desktop Application with Electron and Angular

Build a Desktop Application with Electron and Angular

Feb 14, 2025 am 10:18 AM

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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()
})
Copy after login
Copy after login

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",
  // [...]
}
Copy after login
Copy after login

__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 ."
  },
  // [...]
}
Copy after login
Copy after login

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

npm run start:electron
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

Next, define the openModal() function:

cd ~
ng new electron-angular-demo
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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()
})
Copy after login
Copy after login

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",
  // [...]
}
Copy after login
Copy after login
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 ."
  },
  // [...]
}
Copy after login
Copy after login

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
Copy after login
Copy after login

Now, run your desktop application with the following command:

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

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles