Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

A first app by hand

An Electron project is an ordinary npm project with Electron installed as a dependency. Building it by hand from three files makes it clear what each part does. In the next lesson a ready-made tool will do the same.

Creating the project

mkdir notes
cd notes
npm init -y
npm install --save-dev electron

npm init -y creates package.json, and the second command downloads Electron into node_modules. Electron goes into devDependencies: when the app is built, Electron is embedded into it, so nobody installs it separately.

package.json

Open package.json and make it look like this:

{
  "name": "notes",
  "version": "1.0.0",
  "description": "Simple notes",
  "type": "commonjs",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^38.0.0"
  }
}

The main field tells Electron which file to start with. The start script runs Electron in the current folder. Your version number may be newer — keep the one npm wrote.

main.js

Create main.js in the project root:

// main.js
const { app, BrowserWindow } = require('electron');
 
function createWindow() {
  const win = new BrowserWindow({ width: 800, height: 600 });
  win.loadFile('index.html');
}
 
app.whenReady().then(createWindow);

When Electron is ready, createWindow creates an 800 by 600 window and loads index.html into it.

index.html

Create index.html next to it:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'">
    <title>Notes</title>
  </head>
  <body>
    <h1>Notes</h1>
    <p>The list of notes will be here.</p>
  </body>
</html>

The meta tag with Content-Security-Policy forbids the page to load scripts and styles from anywhere except the app folder. Why it is needed is explained in the security lesson.

Running

npm start

A window opens with the "Notes" heading and the page text. Above the page is Electron's default menu with File, Edit and View. Close the window and the app exits; the terminal shows the command prompt again.

Structure

notes/
├── node_modules/
├── index.html
├── main.js
├── package.json
└── package-lock.json

Later preload.js, renderer.js and styles.css will be added to this folder.

Common mistake

If the main field points to a file that does not exist, for example the index.js left over from npm init, Electron shows an error window saying it cannot find the app. Check that the name in main matches the main process file name.

Thanks for reading!

Donate to the site — we work hard for you.