Table of Contents
Creating cross-platform applications can significantly streamline your development process, allowing you to reach users on Windows, macOS, and Linux with a single codebase. Electron is a popular framework that enables developers to build desktop apps using web technologies like HTML, CSS, and JavaScript. This step-by-step tutorial will guide you through creating your first Electron app.
Prerequisites
- Basic knowledge of JavaScript, HTML, and CSS
- Node.js installed on your computer
- A code editor such as Visual Studio Code
Step 1: Set Up Your Project
Create a new directory for your project and navigate into it using your terminal or command prompt. Initialize a new Node.js project with the following command:
npm init -y
Step 2: Install Electron
Install Electron as a development dependency:
npm install electron --save-dev
Step 3: Create Main Script
Create a file named main.js in your project directory. This will contain the code to launch your application:
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
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();
}
});
Step 4: Create HTML File
In the same directory, create an index.html file with a basic webpage:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
<p>This is a cross-platform desktop application.</p>
</body>
</html>
Step 5: Update package.json
Open your package.json and add a start script:
"scripts": {
"start": "electron ."
}
Step 6: Run Your App
In your terminal, start the application with:
npm start
Conclusion
You have successfully created a basic cross-platform desktop application using Electron. From here, you can enhance your app with additional features, styles, and functionalities to suit your needs. Electron's extensive documentation and community support make it easy to expand your project further.