Building Your First App

Getting Started

Now that you understand Electron's architecture, let's build your first application. We'll create a simple desktop app with a basic window and some content.

Use Electron APIs to open windows and load content into them.

Project Structure

Your first Electron app needs at least two files:

  • Create main.js - The main process entry point
  • Create index.html - The web page to display in the window

Creating the Main Process File

Create a main.js file in your project root. This file will contain the main process code that creates the application window:

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

function createWindow() {
  // Create the browser window
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  // Load the index.html file
  mainWindow.loadFile('index.html');
}

// This method will be called when Electron has finished initialization
app.on('ready', createWindow);

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

// On macOS, re-create window when dock icon is clicked
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

Creating the HTML File

Create an index.html file with your application's user interface:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>My First Electron App</title>
</head>
<body>
  <h1>Hello, Electron!</h1>
  <p>Welcome to your first Electron application.</p>
</body>
</html>

Configuring package.json

Update your package.json to set the main entry point and add a start script:

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

Running Your App

Now you can run your Electron application:

npm start

This command will launch your first Electron application in a new window!

Next Steps

  • Add more functionality to your application
  • Experiment with different window options and sizes
  • Add CSS styling to your HTML
  • Implement JavaScript interactions in the renderer process
  • Learn about IPC for communication between processes