Building a Desktop App with Electron

Electron is a powerful framework that allows you to build desktop applications using web technologies like HTML, CSS, and JavaScript. In this post, I’ll walk you through how to set up and run a simple Electron app locally using Visual Studio Code.


1. Check Node.js Installation

Electron runs in a Node.js environment, so you’ll need to have Node.js installed.

Verify Installation

Open the terminal in Visual Studio Code (Ctrl + `) and run:

node -v
npm -v

If both commands return version numbers, Node.js is properly installed. If not, download and install the latest LTS version from the official Node.js website.


2. Create and Initialize Your Project Folder

Create a new folder and open it in Visual Studio Code.

mkdir my-electron-app
cd my-electron-app

Initialize the project:

npm init -y

This creates a package.json file with default settings.


3. Install Electron

Install Electron as a development dependency:

npm install electron --save-dev

Once installed, you’ll see a node_modules folder and a package-lock.json file.


4. Set Up Basic Files

Create the following file structure:

my-electron-app
    main.js         // Main process
    index.html      // HTML to render
    package.json    // Project configuration

main.js

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Hello, Electron!</h1>
  </body>
</html>

5. Update package.json

Modify the "scripts" section in package.json to enable app launch:

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

6. Run the App

In the terminal, run:

npm start

An Electron window will open displaying the content from index.html.