Electron From Scratch

Let’s get underway developing a cross-platform, desktop application using Electron.

Electron is a Node.js module. Node.js programs are executed by Google’s V8 JavaScript Engine (Hence our soon-to-be usage of ECMA Script 6) and uses libuv for cross-platform I/O via it’s own bindings library.

nodejs-architecture

Table of Contents

Configuring a Node.js Project

First and foremost, we’re going to need NPM (Node Package Manager) and Node.js installed. I’m skipping these installations because they’re platform specific. Get them installed, then use NPM to initialize our project directory by creating a package.json file.

Tip: I initialize my Git repository in the directory, and set a remote first, because the above command will add the Git repository information to the package.json file automatically.

Once we have a package.json file we can use NPM to download the Electron module and its dependencies into the project directory.

The -g argument tells NPM to add the electron executable to your $PATH environment variable. This will come in handy later. You should see a tree view of Electron’s dependencies. These are all installed in a /node_modules directory by default.

screenshot_2016-12-07_20-33-31

Let’s create the application’s injection point now.

Next, let’s tell Node.js that main.js is the injection point. Add the following to the scripts node in the package.json file.

Now add a single line to the main.js file.

screenshot_2016-12-06_22-20-50

We should be able to run the application now, and see output in the console!

screenshot_2016-12-06_22-21-00

Creating a Bare-Bones Electron Application

We’ve got all of the modules in the /node_modules directory at our disposal. In order to get an Electron window appearing on our screen, we’ll require the module and instantiate an Electron application in the main.js file.

When the application is ready, it will create a browser window, and load Google’s homepage.

screenshot_2016-12-06_22-40-23

Routing with Express and View Templating with EJS

To architect our Electron application using the popular REST API style of serving stateful views,  we’ll use another node module called Express.

The –save argument is telling npm to write the Express version in the package.json with the rest of the dependencies.

screenshot_2016-12-07_20-12-00

Next, let’s install EJS.

By default, the EJS engine looks for views in a views folder. Let’s make our first view!

Woot!

Lets get back inside main.js and write some code to display our view instead of Google.

Now we’ve got a basic framework to write an Electron application in!

screenshot_2016-12-07_20-48-55

Enjoy! 🙂