In the previous chapter, we learned how to install Electron.
In this chapter, we will introduce step by step how to create a simple Electron example.
### 1. Create Project Directory
Open the terminal and execute the following commands:
mkdir my-electron-app
cd my-electron-app
npm init -y
npm install electron --save-dev
The generated structure is as follows:
my-electron-demo/
ββ package.json
ββ main.js
ββ index.html
### 2. Configure package.json
Open package.json and modify it to the following content:
```json
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "TUTORIAL Electron Test",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "latest"
}
}
Explanation:
| Field | Function |
| --- | --- |
| `"main"` | Specifies the main process file to execute when Electron starts |
| `"scripts.start"` | Defines the execution content of the `npm start` command |
| `"electron ."` | Indicates that Electron should run the application in the current directory |
| `"devDependencies"` | Development dependencies, will not be packaged into the final application |
### 3. Write the Main Process File main.js
This is the core control center of Electron, responsible for creating application windows and loading pages.
Create the file main.js and enter the following complete code (with detailed comments):
## Example
```javascript
// main.js ββ Electron main process file
// Import app (controls application lifecycle) and BrowserWindow (creates window) from the electron module
const { app, BrowserWindow } = require('electron');
// Node.js built-in module, used for joining file paths
const path = require('path');
// Create a function to generate the main window
function createWindow() {
// Create a new window instance
const win = new BrowserWindow({
width: 800, // Window width (pixels)
height: 600, // Window height (pixels)
resizable: true, // Whether to allow users to resize the window by dragging (default true)
title: "TUTORIAL Electron Test", // Window title, displayed in the title bar
webPreferences: {
// Web page runtime configuration
contextIsolation: true, // Enable context isolation (security recommended)
nodeIntegration: false, // Prohibit direct use of Node.js in web pages
}
});
// Load the local index.html file into the window
// path.join(__dirname, 'index.html') returns the path to index.html in the current directory
win.loadFile(path.join(__dirname, 'index.html'));
// Open developer tools (optional, convenient for debugging)
// win.webContents.openDevTools();
}
// When Electron initialization is complete, the ready event of app is triggered
// app.whenReady() returns a Promise, after execution calls createWindow()
app.whenReady().then(createWindow);
// Triggered when all windows are closed (only effective outside macOS)
app.on('window-all-closed', () => {
// process.platform returns the operating system platform
// macOS platform value is 'darwin', on macOS the program is generally kept resident
if (process.platform !== 'darwin') {
app.quit(); // Exit the application
}
});
// macOS special logic: recreate window when clicking Dock icon
app.on('activate', () => {
// If no windows are currently open, create a new one
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Explanation:
| Concept | Description |
| --- | --- |
| **Main process** | The script that runs first after Electron starts, responsible for window creation, menu control, system APIs, etc. |
| **BrowserWindow** | Used to create a browser window, loading web page content (HTML files or URLs). |
| **app.whenReady()** | Ensures that the window is created only after Electron initialization is complete, otherwise errors may occur. |
| **win.loadFile()** | Loads a local HTML file. Can also use `win.loadURL('https://example.com')` to load a website. |
| **contextIsolation** | Isolates web page scripts from the Node environment, improving security (officially recommended). |
| **nodeIntegration** | If set to `true`, Node.js can be used directly in the page (but has security risks). |
| **window-all-closed** | Exits the application when all windows are closed (effective on Windows/Linux). |
### 4. Write the Render Page index.html
Create the index.html file and enter the following content:
## Example
body {
margin: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
font-family: "Segoe UI", Arial, sans-serif;
background: #f5f7fa;
}
.box {
text-align: center;
background: white;
padding: 40px 60px;
border-radius: 12px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}
h1 {
margin: 0 0 10px;
color: #333;
}
p {
margin: 0;
color: #666;
}
Hello, Electron!
TUTORIAL Electron Test. This is your first Electron desktop application 🎉
### 5. Run the Project
Return to the terminal and execute:
npm start
After running, you will see a desktop window displaying:
Hello, Electron!
TUTORIAL Electron Test. This is your first Electron desktop application 🎉
!(#)