Electron is a popular framework that allows developers to build cross-platform desktop applications using web technologies like HTML, CSS, and JavaScript. Setting up an Electron project can seem daunting for beginners, but with a few simple steps, you can have your application up and running in no time. This guide provides a step-by-step process to help you get started with Electron.

Prerequisites

  • Node.js installed on your computer
  • A code editor such as Visual Studio Code
  • Basic understanding of JavaScript and command line

Step 1: Initialize Your Project

Open your terminal or command prompt and create a new directory for your project. Navigate into the directory and initialize a new Node.js project by running:

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

Step 2: Install Electron

Install Electron as a development dependency by running:

npm install electron --save-dev

Step 3: Create Main Files

In your project directory, create a new file named main.js. This file will contain the main process code for your Electron app. Also, create an index.html file for the user interface.

main.js

Add the following code to main.js:

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

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
  });

  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

Add the following code to index.html:

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

Step 4: Update package.json

Open package.json and add a start script. It should look like this:

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^latest"
  }
}

Step 5: Run Your Electron App

In your terminal, start your application by running:

npm start

Your Electron window should now open displaying "Hello, Electron!". From here, you can begin customizing your application with additional features and UI elements.

Conclusion

Setting up an Electron project involves initializing a Node.js environment, installing Electron, creating main and HTML files, updating your package.json, and running your app. With these steps completed, you are ready to explore more advanced Electron features and build powerful desktop applications.