Building your First Electron App.
Electron is a framework for building cross-platform desktop apps using JavaScript, HTML, and CSS. It embeds Chromium and Node.js, allowing a single JavaScript codebase to run on Windows, macOS, and Linux without native development experience.
To use Electron, you need to install Node.js. It's recommended to use the latest LTS version.
Electron apps follow the same general structure as other Node.js projects. To start, create a folder and initialize an NPM package.
mkdir my-electron-app && cd my-electron-app && npm init
The interactive init command will prompt you to set fields in your config. For this tutorial, please ensure the entry point is set to main.js.
Install the electron package into your app's devDependencies.
npm install --save-dev electron
In the scripts field of your package.json config, add a start command
{
"scripts": {
"start": "electron ."
}
}
The start command allows you to open your app in development mode.
领英推荐
npm start
At this stage, your app will immediately throw an error telling you that it cannot find an app to run.
The entry point of an Electron application is its main script, which controls the main process running in a full Node.js environment. This process manages the app's lifecycle, displays native interfaces, performs privileged operations, and handles renderer processes.
Electron locates this script using the main field in the app's package.json, set during app setup. To initialize the main script, create an empty file named main.js in the root of your project.
// main.js
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
Create an index.html file in the root folder of your project
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Electron App</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
The start command allows you to open your app in development mode.
npm start
This basic structure will display "Hello World" as a heading in your app's window.
In the next Part, we will make a TODO desktop application. Till then play with Electron.