Quickly start a new Electron software project

; Date: Wed Jun 20 2018

Tags: Node.JS »»»» Electron

If Electron encapsulates the Chromium web browser to support running GUI applications, isn't it a complex platform to use? Isn't it complex to get started with Electron? Yes, there is a fair amount of complexity under the hood of Electron. Electron really is the guts of the Google Chrome web browser, encapsulated in a Node.js runtime, letting Node.js programmers easily develop desktop GUI applications using web technology. That was a mouthfull to describe, and getting a fully polished application up and running has some complexity. Thanks to starter projects maintained by the Electron team, getting a skeleton application running is quick.

What we'll do is walk through one of the starter applications and discuss what's there.

This article is part of a series on kicking the tires of Electron application development. See:

Namely: (github.com) https://github.com/electron/electron-quick-start

QUICK START:

$ git clone https://github.com/electron/electron-quick-start
Cloning into 'electron-quick-start'...
remote: Counting objects: 289, done.
remote: Total 289 (delta 0), reused 0 (delta 0), pack-reused 289
Receiving objects: 100% (289/289), 59.89 KiB | 901.00 KiB/s, done.
Resolving deltas: 100% (133/133), done.
$ cd electron-quick-start
$ npm install

> electron@2.0.2 postinstall /Volumes/Extra/sourcerer/004-electron/electron-quick-start/node_modules/electron
> node install.js

Downloading SHASUMS256.txt
[============================================>] 100.0% of 5.33 kB (5.33 kB/s)
electron@2.0.2 node_modules/electron
├── @types/node@8.10.20
├── extract-zip@1.6.7 (debug@2.6.9, yauzl@2.4.1, mkdirp@0.5.1, concat-stream@1.6.2)
└── electron-download@3.3.0 (semver@5.5.0, home-path@1.0.6, minimist@1.2.0, path-exists@2.1.0, rc@1.2.8, debug@2.6.9, sumchecker@1.3.1, fs-extra@0.30.0, nugget@2.0.1)

$ npm start

> electron-quick-start@1.0.0 start /Users/David/electron-quick-start
> electron .

Ah, there's a pre-requisite that's obvious - first, install Node.js. But if you're here you probably already have Node.js installed. If not, consult:

The skeleton electron app in its full glory

Okay, we're done right? That's all there is? Before we leave, let's take a quick look at the source

The files associated with the skeleton application

It's a small list of files, so it'll be quick to go over this. The file hierarchy isn't what gets used in larger Electron applications, but it works in this case.

package.json

{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "repository": "https://github.com/electron/electron-quick-start",
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial",
    "demo"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "^2.0.0"
  }
}

Let's start with the package.json. It declares main as main.js, which we'll look at shortly.

The start script runs electron .. The electron command was installed by the electron package -- see the devDependencies section -- and provides the method to launch an Electron application. Running the command without options gives this help text:

$ electron

  Electron 2.0.2 - Build cross platform desktop apps with JavaScript, HTML, and CSS
  Usage: electron [options] [path]

  A path to an Electron app may be specified. It must be one of the following:
    - index.js file.
    - Folder containing a package.json file.
    - Folder containing an index.js file.
    - .html/.htm file.
    - http://, https://, or file:// URL.

  Options:
    -d, --default         Run the default bundled Electron app.
    -i, --interactive     Open a REPL to the main process.
    -r, --require         Module to preload (option can be repeated).
    -v, --version         Print the version.
    -a, --abi             Print the Node ABI version.

So, electron . uses the scenario Folder containing a package.json file.

main.js

As the name implies, this module initializes the application.

const {app, BrowserWindow} = require('electron')

The Electron team likes to destructure objects like this - and this idiom is meant to be similar to ES6 modules.

The app object is a handle for the application. BrowserWindow is a class that encapsulates, as the name implies, a top-level Browser window.

Recall that Electron encapsulates the guts of Chrome. That means a Window in an Electron application is really a Browser window.

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

The app object provides an on EventEmitter listener mechanism you use as so. The ready event is emitted when the application is, well, ready. The skeleton application will also call createWindow via an activate event.

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

We initialize a new BrowserWindow, assigning it to a global-to-this-module variable. In the next line we load an index.html into that browser -- the actual user interface is written in HTML. Interactivity is implemented by browser-style JavaScript running inside the BrowserWindow.

The closed event is emitted when the user elects to close the application. In this case it sets mainWindow to null, and then if all windows are closed we get this event:

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

When all windows are closed, we call app.quit() to close the application process. For Mac OS X this is written to require the user to type CMD+Q instead.

That's the basic of launching the application, making something appear, and quitting the application.

index.html

The user interface is implemented with HTML code. Such as:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.

    <script>
      // You can also require other files to run in this process
      require('./renderer.js')
    </script>
  </body>
</html>

For the most part this is HTML you'd write on a regular website. It's nice clean modern HTML5 code. Compare the code here, especially the first few <script> tags, with the screen capture earlier.

But... that last <script> tag uses a require statement. What's up with that?

Electron brings a few Node.js features into what looks like browser-side JavaScript. Such as the ability to use require to load modules.

In this case it loads in ./renderer.js which is:

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

What's that about a renderer process?

Electron's process structure

Electron has a Main process and one or more Renderer processes. The Main process is the one which runs the script listed in the main tag of package.json. There can be only one Main process.

Each web page in Electron runs in its own Renderer process. This is because of Chromium's multi-process architecture, where each open browser tab in Chrome has its own process. Electron Renderer processes follow the same model.

Electron provides an inter-process-communication system so the two can communicate. Events are sent between the Main process and the Renderer processes. A Renderer process can request the Main process take some actions, etc.

From the documentation ( (electronjs.org) https://electronjs.org/docs/tutorial/application-architecture):

In web pages, calling native GUI related APIs is not allowed because managing native GUI resources in web pages is very dangerous and it is easy to leak resources. If you want to perform GUI operations in a web page, the renderer process of the web page must communicate with the main process to request that the main process perform those operations.

Conclusion

That's a good basis for beginning to understand Electron application development.

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)