Electron Foundations & Hello World
7 min read
Electron Foundations & Hello World
Before you write a single line of code, you need to understand the landscape of what you are building. This guide breaks down the absolute fundamentals of Electron, how to set up your environment using modern industry standards, and how to wire up your very first desktop application.
1. The "Why" Before the "How": Desktop Apps with Web Tech ๐
The Problem
Historically, building a desktop application meant maintaining multiple codebases. If a company wanted an app for Windows, macOS, and Linux, they had to hire developers who knew C++ or C# for Windows, Swift or Objective-C for macOS, and something else entirely for Linux. This approach was slow, incredibly expensive, and led to inconsistent features across different operating systems. Developers would often weep softly into their keyboards when asked to port a simple text editor to three different operating systems.
The Definition
Electron is an open-source framework created by GitHub that allows developers to build cross-platform desktop graphical user interfaces (GUIs) using standard web technologies: HTML, CSS, and JavaScript. It does this by combining the Chromium rendering engine (the core of Google Chrome) and the Node.js JavaScript runtime into a single executable binary.
How It Solves the Problem
By bundling a web browser (Chromium) and a backend runtime (Node.js) together, Electron allows you to write your application exactly once. Your UI is built just like a standard website, but instead of running in a user's regular web browser, it runs inside a dedicated, standalone window powered by Electron. The framework then handles the translation of your web code into native graphical application windows across Windows, macOS, and Linux.
Industry Fact: If you have used Visual Studio Code, Discord, Slack, or Figma's desktop app, you have already used an Electron application. They are everywhere.
Under the Hood: Because Electron literally embeds an entire Chromium browser inside your app, the tradeoff for this convenience is file size and memory usage. A simple "Hello World" app will be significantly larger (often over 100MB) than a native application because it carries an entire browser engine with it.
2. Setting Up Your Environment: Node.js and npm ๐ ๏ธ
The Problem
A standard web browser is heavily sandboxed for security. If you visit a website, that website cannot read files on your local hard drive or execute system-level commands. However, desktop applications need this power. They need to save files, read configurations, and interact with the operating system. Standard JavaScript running in a browser cannot do this.
The Definition
Node.js is a back-end JavaScript runtime environment that executes JavaScript code outside a web browser. npm (Node Package Manager) is the default package manager for Node.js, allowing developers to download and manage external code libraries (packages) within their projects.
How It Solves the Problem
By integrating Node.js, Electron grants your JavaScript code unrestricted access to the underlying operating system. You can use standard Node.js built-in modules like fs (File System) to read and write files directly from the user's computer.
Hands-on Practice: Installation
Let's set up a standard boilerplate. We will use npm to initialize our project and install Electron.
- Install Node.js: Download and install the latest Long Term Support (LTS) version of Node.js from their official website. (This automatically installs
npm). - Initialize the Project: Open your terminal and create a new directory for your app.
mkdir my-electron-app
cd my-electron-appNext, initialize a new Node project. The -y flag skips the interactive questionnaire and uses default values.
npm init -y- Install Electron: Install Electron as a development dependency.
npm install electron --save-devIndustry Standard: Why --save-dev? In industry practice, Electron is treated as a development dependency. When your application is finally built and packaged for users (using tools like Electron Forge or Electron Builder), the bundler will automatically grab the correct Electron binaries. You don't need Electron as a standard production dependency in your final package.
3. Your First Desktop App: "Hello World" Electron Style ๐ฅ๏ธ
The Problem
A standard Node.js script just runs in the terminal and exits. A standard HTML file just sits there until a browser opens it. To create a desktop app, we need a mechanism that launches a persistent background process, listens to the operating system, and forcefully opens a graphical window to display the HTML.
The Definition
Electron apps are divided into two distinct types of processes:
- The Main Process: The background script (Node.js) that acts as the entry point of your application. It controls the lifecycle of the app and manages native OS elements (like opening windows, menus, and system trays).
- The Renderer Process: The actual web page (HTML/CSS/JS) displayed inside the window created by the Main Process.
Imagine you are running a high-end restaurant. The Main Process is the restaurant manager. The manager doesn't cook the food; instead, they handle the building, unlock the front doors, and assign tables (windows). The Renderer Process is the actual table where the dining experience (the UI) happens. You can have multiple tables (Renderer Processes), but only one manager (Main Process) controlling the building.
Hands-on Practice: The Code
Create two files in your project directory: main.js and index.html.
index.html (The Renderer / The UI)
This is just standard HTML. Nothing special here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World App</title>
</head>
<body>
<h1>Hello, Electron World! ๐</h1>
<p>We are running desktop apps with web tech.</p>
</body>
</html>main.js (The Main Process / The Manager)
This is where the magic happens. We import app (which controls the application's event lifecycle) and BrowserWindow (which creates and manages app windows) from the electron module.
const { app, BrowserWindow } = require('electron');
// Function to generate a graphical window
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
// Load our HTML file into the window
mainWindow.loadFile('index.html');
};
// Wait for Electron to be fully initialized before creating windows
app.whenReady().then(() => {
createWindow();
// macOS specific behavior: Re-create a window if the dock icon is clicked and no windows are open
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Windows/Linux specific behavior: Quit the app when all windows are closed
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});Why the platform checks? In Windows and Linux, closing all windows typically quits the application entirely. On macOS (
darwin), applications usually stay running in the background (in the Dock) until the user explicitly quits withCmd + Q. The code above handles this industry-standard usability quirk.
4. Understanding package.json and Entry Points ๐
The Problem
When you type a command to run your app, your computer is essentially blind. It sees a folder full of files (index.html, main.js, package-lock.json, the massive node_modules folder) and has no idea which file it should execute to start the application.
The Definition
The package.json file is the manifest or "instruction manual" for your project. An Entry Point is a specific file designated inside this manifest that the runtime must execute first to boot up the application.
How It Solves the Problem
By defining an exact entry point and creating a shortcut "script" inside package.json, we give developers and the system a standardized, foolproof way to start the app without guessing.
Hands-on Practice: Wiring it up
Open the package.json file that was generated earlier by npm init -y. It will look something like this:
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^41.0.0"
}
}We need to make two crucial changes:
- Change the
"main"property from"index.js"to"main.js". This tells Electron thatmain.jsis the entry point (the Main Process). - Add a
"start"script to the"scripts"object.
Update your package.json to look like this:
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "My first desktop app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Your Name",
"license": "MIT",
"devDependencies": {
"electron": "^41.0.0"
}
}Starting the App
Now, go back to your terminal and run:
npm startUnder the Hood: When you type npm start, npm looks into your package.json for the start script. It sees the command electron .. The . means "look in the current directory". Electron boots up, reads package.json, finds "main": "main.js", and executes main.js in its embedded Node.js environment. Your main.js script then tells the operating system to open a window and load index.html.
Suddenly, a desktop application appears on your screen! ๐
References & Extra Reading
Challenge
Challenge: Create the Core Files for an Electron Application
Your task is to write the complete source code for the three essential files of a new Electron application: package.json, main.js, and index.html. Follow the specifications precisely for each file.
1. package.json Specifications:
- Set the
nameproperty to"electron-practice-app". - Set the
versionproperty to"1.0.0". - Configure the application's entry point to be
main.js. - Add a
startscript that will launch the application using theelectroncommand in the current directory.
2. main.js Specifications:
- Import the
appandBrowserWindowmodules from theelectronpackage. - Create an asynchronous function named
createWindow. - Inside
createWindow, instantiate a newBrowserWindowwith awidthof 1024 and aheightof 768. - Load the
index.htmlfile into the browser window. You will need to use Node.js'spathmodule to create an absolute path to the file. - Use the
app.whenReady()lifecycle method to call yourcreateWindowfunction. - Add an event listener for the
window-all-closedevent. This listener should quit the app, but only if the user is not on macOS (i.e.,process.platform !== 'darwin'). - Add an event listener for the
activateevent. This listener should callcreateWindow()if there are no windows open. This is for macOS compatibility.
3. index.html Specifications:
- Create a valid HTML5 document.
- Set the document title to
"Electron Core". - Add an
<h1>element with the text"Main Process and Renderer Process Communication". - Add a
<p>element with the text"This is the UI running in the Renderer Process.".
Expected result
Expected Code Structure
Your final code should consist of three distinct blocks, one for each file, matching the content below precisely.
package.json
{
"name": "electron-practice-app",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
}
}main.js
const { app, BrowserWindow } = require('electron');
const path = require('path');
const createWindow = () => {
const win = new BrowserWindow({
width: 1024,
height: 768
});
win.loadFile(path.join(__dirname, '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();
}
});index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Electron Core</title>
</head>
<body>
<h1>Main Process and Renderer Process Communication</h1>
<p>This is the UI running in the Renderer Process.</p>
</body>
</html>