Agenda:

This article explains usage of electron & angular together to build an desktop application. We will understand how methodology of Electron JS can be mixed up with tactics of Angular to develop a desktop application. So as a prerequisites, you should have basic knowledge of Electron JS and Angular. Let us get started.

Get started:

Follow these basics steps:

  • Installing Angular CLI npm i -g @angular@cli.
    **it installs angular cli globally.
  • Creating a new angular application. Execute ng new electron-angular.
    **electron-angular is application name
  • Install Electron JS by executing npm i electron --save-dev.
    **it installs electron as dev dependency.

Add main.js at root of your project and code snippet below:

  1. const { app, BrowserWindow } = require("electron");
  2. const path = require("path");
  3. const url = require("url");
  4.  
  5. let win;
  6.  
  7. function createWindow() {
  8. win = new BrowserWindow({ width: 800, height: 600 });
  9.  
  10. // load the dist folder from Angular
  11. win.loadURL(
  12. url.format({
  13. pathname: path.join(__dirname, `/dist/index.html`),
  14. protocol: "file:",
  15. slashes: true
  16. })
  17. );
  18.  
  19. win.on("closed", () => {
  20. win = null;
  21. });
  22. }
  23.  
  24. app.on("ready", createWindow);
  25.  
  26. // on macOS, closing the window doesn't quit the app
  27. app.on("window-all-closed", () => {
  28. if (process.platform !== "darwin") {
  29. app.quit();
  30. }
  31. });
  32.  
  33. // initialize the app's main window
  34. app.on("activate", () => {
  35. if (win === null) {
  36. createWindow();
  37. }
  38. });

It is time to update package.json as follows:

  1. (
  2. ...
  3. "main": "main.js",
  4. ...
  5. "scripts": {
  6. ...
  7. "electron": "ng build --base-href ./ && electron ."
  8. ...
  9. },
  10. ...
  11. }

Just one last but necessary change need to make, is to update outputPath as "outputPath": "dist" in angular.json Here, i just removed the project directory name from the path.

Here you go !! time to start our application. npm run electron. We have angular component loaded in an electron window.

Conclusion:

In this article we learnt using electron along with angular to build a desktop application.

Good Bye 👋 !! until I write again. Code well, Cook good.