Electron.js

Get started with Electron.js, learn how to build a simple hello world app from scratch.

So many desktop apps are currently using Electron.js: Slack, Telegram, Spotify… So go on and follow the next basic steps. First step is to install it as follow:

# npm i -g electron

Now we are going to generate a simple project structure:

$ cd /tmp 
$ mkdir hello-world
$ cd hello-world 
$ touch main.js package.json index.html

Main file

This file starts the app and creates a webview. This is the main file of our app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const electron      = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
let win;

/**
* We declare a createWindow function that creates our window, with
* dimensions and using index.html as content. We indicate that when the
* (ready) application is started the function is called.
*/
const createWindow = () => {
win = new BrowserWindow({width: 800, height: 600});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
win.on('closed', () => win = null);
};
app.on('ready', createWindow);

// Closes all windows after close the app
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});

// Generates the view when come from minimizes
app.on('activate', () => {
if (win === null) {
createWindow();
}
});

Our package.json

1
2
3
4
5
{
"name": "your-app",
"version": "0.1.0",
"main": "main.js"
}

Index html file

Our main view:

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

Start the app

$ cd our_project_path
$ electron .

References