Table of Contents
Are you interested in building cross-platform desktop applications with ease? Electron is a popular framework that allows developers to create desktop apps using web technologies like HTML, CSS, and JavaScript. This guide will walk you through building your first Electron app in just 30 minutes.
What is Electron?
Electron is an open-source framework developed by GitHub. It combines Chromium and Node.js to enable developers to build desktop applications that work seamlessly across Windows, macOS, and Linux. Many well-known apps like Visual Studio Code, Slack, and Discord are built with Electron.
Prerequisites
- Node.js installed on your computer (download from nodejs.org)
- A code editor like Visual Studio Code
- Basic knowledge of JavaScript and HTML
Step 1: Set Up Your Project
Create a new folder for your project and open it in your terminal or command prompt. Initialize a new Node.js project by running:
npm init -y
Step 2: Install Electron
Install Electron as a development dependency:
npm install electron --save-dev
Step 3: Create Main Files
In your project folder, create a file named main.js. This will be your main process script. Also, create an index.html file for your app's UI.
main.js
Paste the following code into 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
Paste the following code into index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My First Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
<p>This is your first desktop app built with Electron.</p>
</body>
</html>
Step 4: Update package.json
Open package.json and add a start script:
"scripts": {
"start": "electron ."
}
Step 5: Run Your App
In your terminal, start the app with:
npm start
Congratulations!
You have successfully built and run your first Electron desktop application in just 30 minutes! From here, you can explore adding more features, integrating APIs, and customizing your app's UI.