Skip to main content
imvinojanv.dev
  • About
  • Blog
  • Projects
  • Snippets

Command Palette

Search for a command to run...

imvinojanv.dev
Open to Hire

I'm always open to discussing software engineering work or partnership.

HomeAboutResumeUses
BlogProjectsSnippets
© 2026 Vinojan Veerapathirathasan —— Colombo, Sri Lanka.
MediumGitHubLinkedInRSS
Back

Build Your Own Cross-Platform Desktop App.

Explore how Electron bridges the gap between web and desktop platforms — A detailed guide to build a desktop app.

Published on July 11, 2024
7 min read
Build Your Own Cross-Platform Desktop App.

Hi there 👋,

Welcome to another exciting exploration of a transformative approach to desktop application development — Electron.

📑 In this article, we’ll dive deep into the workings of Electron, revealing how this powerful framework enables you to use web technologies to create cross-platform desktop apps effortlessly. Ready to simplify your development process and extend the reach of your applications across multiple operating systems? Let’s get started! 🎊

⚛ Electron is a robust framework that enables developers to create desktop applications using web technologies like HTML, CSS, and JavaScript. It has rapidly gained popularity and is now used by many large-scale applications such as Slack, Microsoft Teams, Trello, Discord and Visual Studio Code.

The core idea behind Electron is simple yet powerful: it combines Chromium’s rendering library and the Node.js runtime, allowing developers to build cross-platform applications that run on Windows, macOS, and Linux. This approach means that you can write your application code once and run it everywhere, leveraging the vast ecosystem of web development tools and libraries.

Let’s build an app with me 🎉

#1: Initializing a New Node.js Project

The first step in building an Electron application is setting up your Node.js project environment. This involves creating a new folder for your project and initializing it with npm:

mkdir my-electron-app
cd my-electron-app
npm init -y

This command creates a package.json file with default values, which will manage all your project dependencies.

#2: Installing Electron

To add Electron to your project, install it as a development dependency:

npm install --save-dev electron

This command will download Electron and integrate it with your project, allowing you to build and test your application locally.

#3: Creating Essential Files

An Electron app typically requires at least two files:

  • index.html: The main HTML file for your app's UI.
  • main.js: The main JavaScript file that runs the Electron app and manages the windows.
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>System Information App</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
main.js
const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");
 
let win;
 
function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    icon: path.join(__dirname, "img", "icon.ico"),
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      contextIsolation: true,
      nodeIntegration: false,
      enableRemoteModule: false,
      worldSafeExecuteJavaScript: true,
      allowRunningInsecureContent: false,
    },
  });
 
  win.loadURL(
    url.format({
      pathname: path.join(__dirname, "index.html"),
      protocol: "file:",
      slashes: true,
    }),
  );
 
  win.on("closed", () => {
    win = null;
  });
}
 
app.on("ready", createWindow);
 
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

NOTE: Please make sure to place your app icons and images into the correct path (/img/icon.png).

#4: Configuring the Start Script

package.json
"scripts": {
  "start": "electron ."
}

To run your application:

npm start

NOTE: We will create preload.js file, If you get any error on this stage, just comment that line on main.js file and run the application

#5: Styling the App using Bootstrap

For quick and appealing UI design, you can use a CSS framework. Here’s how to integrate a Bootstrap CSS from Bootswatch:

  • Download your chosen CSS file from Bootswatch and save it into your project directory (/style/bootstrap.min.css)
  • Import the CSS file in your index.html to style the application:
<link rel="stylesheet" href="bootstrap.min.css" />

#6: Enhancing Functionality with JavaScript

To interact with native elements and perform OS-level operations, Electron uses two JavaScript contexts:

  • Preload Script (preload.js): This script runs before the web page is loaded, in a privileged environment with access to Node.js APIs but in a secure manner.
preload.js
const { contextBridge, ipcRenderer } = require("electron");
 
contextBridge.exposeInMainWorld("api", {
  getNodeVersion: () => process.versions.node,
  getChromeVersion: () => process.versions.chrome,
  getElectronVersion: () => process.versions.electron,
  getProcessIdentifier: () => process.pid,
  getPlatformInformation: () => process.platform,
});
  • Renderer Script (renderer.js): This script interacts with the web page directly, manipulating the DOM as needed.
renderer.js
document.addEventListener("DOMContentLoaded", () => {
  const outputDiv = document.getElementById("output");
  outputDiv.innerHTML = `
        <div class="mb-4">
            <h2>App Version</h2>
            <ul class="list-group">
                <li class="list-group-item">Node: ${window.api.getNodeVersion()}</li>
                <li class="list-group-item">Chrome: ${window.api.getChromeVersion()}</li>
                <li class="list-group-item">Electron: ${window.api.getElectronVersion()}</li>
            </ul>
        </div>
 
        <div class="mb-4">
            <h2>System Specifications</h2>
            <ul class="list-group">
                <li class="list-group-item">Process Indentifier: ${window.api.getProcessIdentifier()}</li>
                <li class="list-group-item">Platform: ${window.api.getPlatformInformation()}</li>
            </ul>
        </div>
    `;
});

Create these files and set up basic interactions, such as sending information from the preload script to the renderer script using Electron’s context bridge.

To see those changes on the app, modify index.html like this:

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>System Information App</title>
    <link rel="stylesheet" type="text/css" href="./style/bootstrap.min.css" />
  </head>
  <body>
    <div class="container mt-4">
      <h1>System Infomation App</h1>
      <p>Developed by imvinojanv</p>
      <div id="output"></div>
    </div>
    <script src="./renderer.js"></script>
  </body>
</html>

Now, you can run the application and see the changes how it’s beautiful 🎏

#7: Continuous Development with Electronmon

To improve the development experience by automatically restarting your app upon file changes, use electronmon:

npm install --save-dev electronmon

Change your start script to use electronmon:

package.json
"scripts": {
  "start": "electronmon ."
}

Now, when you run npm start, electronmon will monitor changes and reload your app, making development faster and more iterative.

Package and Distribute you Application

Option 1: Using electron-forge CLI

You’ll need to integrate Electron Forge into your Electron project. If you haven’t already installed Electron Forge, Install the CLI and add it,

npm install --save-dev @electron-forge/cli
npx electron-forge import

This command will modify your project’s configuration to include necessary dependencies and scripts for Electron Forge. It automatically updates your package.json to use Forge's configuration and scripts.

Once Electron Forge is configured, packaging your application is straightforward. Run the following command to create a packaged version of your app that is ready for distribution:

npm run make

This command instructs Electron Forge to compile your application into out folder with all its dependencies and then to create distributable formats based on the makers you’ve defined in your configuration.

Option 2: Using electron-builder

Install electron-builder:

npm install --save-dev electron-builder

Configure the package.json for electron-builder:

package.json
{
  "name": "system-info-desktop-app",
  "version": "1.0.0",
  "description": "Desktop application built with Electron.js",
  "main": "main.js",
  "scripts": {
    "start": "electronmon .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },
  "keywords": ["electron app"],
  "author": "imvinojanv",
  "license": "ISC",
  "build": {
    "appId": "com.imvinojanv.systeminfodesktopapp",
    "productName": "System Info",
    "copyright": "2024 imvinojanv",
    "icon": "img/icon.png",
    "files": [
      "**/*",
      "!**/*.map",
      "!**/*.bat",
      "!**/*test*",
      "!**/db.json",
      "!**/node_modules/*/{CHANGELOG.md,README.md,README,readme.md,readme}"
    ],
    "directories": {
      "buildResources": "assets"
    },
    "win": {
      "target": "nsis",
      "icon": "assets/icon.ico"
    },
    "mac": {
      "target": "dmg",
      "icon": "assets/icon.icns"
    },
    "linux": {
      "target": ["AppImage", "deb"],
      "icon": "assets/icons"
    }
  },
  "devDependencies": {
    "electron": "^31.1.0",
    "electron-builder": "^24.13.3",
    "electronmon": "^2.0.3"
  }
}

Run the build command to package your app:

npm run dist

This command creates platform-specific packages in the dist directory, ready for distribution.

🍃 This guide provided a comprehensive overview of building an Electron application, from initial setup through development and final packaging. With Electron, you have the power to create robust desktop applications using familiar web technologies, streamlining the development process across multiple platforms.


I appreciate you taking the time to read this article.🙌

Before you move on to explore the next article, don’t forget to give your claps 👏 for this article and share with your friends. Stay connected with me on social media. Thanks for your support and have a great rest of your day! 🎊

✍️ Vinojan Veerapathirathasan.

0
0
0
0
0

On This Page

Let’s build an app with me 🎉#1: Initializing a New Node.js Project#2: Installing Electron#3: Creating Essential Files#4: Configuring the Start Script#5: Styling the App using Bootstrap#6: Enhancing Functionality with JavaScript#7: Continuous Development with `Electronmon`Package and Distribute you ApplicationOption 1: Using `electron-forge CLI`Option 2: Using `electron-builder`
Last updated: July 11, 2024