Electron: Build Desktop Applications Using Plain Javascript
Tags: javascript, webdev, beginners, programming
Published: 2023-02-08 14:06:17

The JavaScript ecosystem has proven to be very versatile over the years with great innovations, one of them being the ability to build desktop applications using just Node.js, HTML, CSS, and of course JavaScript.

## ⚛️ What is it?

[Electron](https://electronjs.org/) is a cross-platform shell — a user interface for accessing operating system services both via command line ([CLI](https://en.wikipedia.org/wiki/Command-line_interface)) and graphical user interface ([GUI](https://en.wikipedia.org/wiki/Graphical_user_interface)).

With Electron we can develop desktop applications using HTML, CSS and Javascript — the famous Web technologies. It has integration with Node.js, we can use it to build not only the screens but all the logic of a BackEnd that accesses resources of the operating system — local directories, database in a simpler way.

It is cross-platform — we can install the application on Windows, Linux and MacOS.

## 📖 History

Electron was created by [Cheng Zhao](https://github.com/zcbenz), and released on April 11, 2013 under the name Atom Shell. As soon as May 6, 2014 the Atom code editor on GitHub became open source under the MIT license. In 2015 Atom Shell was renamed to Electron, and as time went by it became more popular and in just two years they managed to create and make available automatic app updates, Windows installers, sending app error logs, desktop notifications, among other features. In 2016 the Windows Store already started accepting Electron apps in its store.

## ⏳ Desktop applications in 2023?

Yes. There are several success cases and needs that we have — as programmers we use the VS Code code editor that was made with Electron, Atom itself the first app made with Electron.

It was also built with Slack, Figma, Twitch, Whatsapp desktop, among other apps that you can find on this site: [https://www.electronjs.org/apps](https://www.electronjs.org/apps)

## 🏛️ Architecture

Electron comes with Chromium browser, an open source project from where Google Chrome came from. All the visuals, windows, etc are rendered in this layer and the BackEnd runs on Node.js. Both have access to each other via RPC (Remote Procedure Call).

Two important concepts around the technology: **main process** and **renderer process.**

The file that is defined in the main property of package.json is called the main process. It is unique throughout the application, responsible for creating the application window(s) through instances of BrowserWindow.

Electron uses Chromium to render the web pages, the multi-process architecture of that tool is used as well, each web page (Electron’s desktop window) runs its own process, which is called the **render process.**

In short, we have Node.js in the main process using the Electron library that makes native calls to the operating system. And the Electron API running the application windows with HTML, CSS, JavaScript and its under-the-hood assets with Chromium.

The windows (FrontEnd) cannot invoke the native resources in order not to break the security of the application, but the communication between both processes — main and rendering, is done through a concept of **inter-process communication** (IPC) using the RPC (Remote Procedure Call) method. For this we have the [ipcRender](https://www.electronjs.org/docs/latest/api/ipc-renderer) and [ipcMain](https://www.electronjs.org/docs/latest/api/ipc-main) APIs.

This is an **advanced topic**, we can create an article just for this. This knowledge is needed when we are going to access a database and other operating system resources with requests made from the application windows (renderer process).

## 📁 Project Structure

Application in Electron, is essentially a Node.js application, needs:

* package.json — Points to the main app file and lists its dependencies

* main.js — Starts the app and creates a browser window for rendering HTML. This is the main process of the app (main process)

* index.html — A web page that gets rendered. This is the renderer process of the app

## 👋 Creating the first project

Prerequisites: Basic knowledge in HTML, CSS, JavaScript, and Node.js.

### Starting the project

Create a folder to make your project and initialize it in Node.js:

    mkdir hi-electron && cd hi-electron && npm init -y

Open the hi electron folder in your code editor. If you are using VSCode use: code .

Install the electron dependency with:

    npm install --save-dev electron

After the installation, the node_modules folder will be created in the root of the project.

In the package.json there will be a property “main” you can change from index.js to main.js this is the main file of the project that we will create next. And in the scripts property change the test to start and put electron main.js for Electron to run the main.js file.

    {
      "name": "hi-electron",
      "version": "1.0.0",
      "description": "",
      "main": "main.js",
      "scripts": {
        "start": "electron main.js"
      },
      "keywords": [],
      "author": "",
      "license": "MIT",
      "devDependencies": {
        "electron": "^22.2.0"
      }
    }

The main.js file will contain the code responsible for creating windows and handling all operating system events.

Let’s create a main.js and index.html file in the root of the project using the terminal if you prefer:

    touch main.js index.html

### 🔃 Adding the Live Reload

Let’s add a lib to live reload the application with every code change we make, this helps a lot in development.

Without it we would have to stop the node process and rerun every comma we change in the code.

    npm install electron-reload

Soon we will see the main.js code that will configure the application and use this lib we have just installed.

### The main.js file

Basically this is the first code of the app with Electron and I’ve commented out every bit of it so you understand. This is the input file that will be executed when we run the npm start command.

Copy and paste this code into the main.js file that we created and read it throughly:

    const { app, BrowserWindow } = require('electron');
    const path = require('path');
    const url = require('url');
    
    // create a basic window
    let win;
    function createWindow() {
      win = new BrowserWindow({width: 800, height: 600});
      win.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
      }));
      win.on('closed', () => {
        win = null;
      });
    }
    
    // create a window when Electron is ready
    app.on('ready', createWindow);
    
    // close the window when all the windows are closed
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit();
      }
    });
    
    // create a window when the app is activated
    app.on('activate', () => {
      if (win === null) {
        createWindow();
      }
    });

### The index.html file

In this file paste this code below, it contains the HTML struture, the CSS styling and the logic in Javascript that will be displayed in the previously created window.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
        body {
          background-color: #f0f0f0;
        }
        header {
          background-color: #f0f0f0;
          padding: 20px;
          text-align: center;
        }
        main {
          background-color: #f0f0f0;
          padding: 20px;
          text-align: center;
        }
        footer {
          background-color: #f0f0f0;
          padding: 20px;
          text-align: center;
        }
      </style>
    </head>
    <body>
      <header>
        <h1>My First HTML Page</h1>
      </header>
      <main>
        <p>My first paragraph.</p>
      </main>
      <footer>
        <p>My first footer.</p>
      </footer>
    </body>
    </html>

### Running the project

Open your terminal and in the root of the project run:

    npm start

## ⚡️ Next steps

 1. **Experiment with the Electron API:** Try building a simple application using the Electron API and get familiar with the various components such as BrowserWindow, Menu, and Tray.

 2. **Develop a full-fledged application:** Once you have a good understanding of the basics, you can start building a more complex application with features like multi-window support, file system access, and native notifications.

 3. **Customize the application’s look and feel:** You can use CSS and JavaScript to customize the appearance of your application and make it look polished and professional.

 4. **Integrate with other technologies: **Electron can be used with a variety of other technologies such as React, Angular, and Vue.js, to build powerful and complex applications.

 5. **Publish your application:** Once your application is complete, you can publish it to the web or package it for distribution on various platforms like Windows, macOS, and Linux.

 6. **Join the Electron community:** Joining the Electron community is a great way to stay up-to-date on the latest developments, learn from other developers, and get help with any challenges you may encounter. There are many online forums, Reddit groups, and GitHub repos dedicated to Electron.

## Conclusion

I really liked the possibility to create a beautiful Desktop application in an easy way, using web technologies, we can use Bootstrap, React, Vue.js, any technology that runs in the browser and makes the screen building (UI) experience easier.

I believe that with HTML, CSS and JS it is easier and faster to implement UI/UX best practices than with Desktop applications made with Java, C#, Visual Basic or Delphi. Let me know what you think about this in the comments.

I think the possibility to reuse web knowledge to develop desktop apps is amazing.

If you have any questions or want to share any tips, please leave a comment below. I would love to read your opinion and feedback!

Thanks for reading! Follow me in this platform to read more programming content. Have a great day, see you soon! 👋