Creating Apps with ElectronJS
Tags: html, javascript, electronjs, electron
Published: 2020-12-07 04:41:18

Twitch, Visual Studio Code, WhatsApp, and Microsoft Teams, just to name a few, are all apps that are created with Electron. But why use it? What is it? What makes it better than another framework? And finally, of course, how do you use it? Let's dive in deep with Electron to answer these questions.

* * *
* * *

# What is ElectronJS, and why to use it?

ElectronJS is a JavaScript framework created to help you create apps, without you having to do all the hard parts. It has built-in crash reporting, debugging and profiling, and notifications among other things. It's open-source and free to use and takes around 5 minutes to convert a pre-existing HTML page or project to a desktop app.

# Basic Electron

First, make sure you have NodeJS and NPM installed, as we'll be using them to install packages, test, and run our app. If you don't have it, you can install it [here](https://nodejs.org/en/). Once it's installed, check it's installed correctly by running the following commands:
```console
node -v
npm -v
```
A basic electron app will consist of the following files:
``` 
my-electron-app/
├── package.json
├── main.js
└── index.html
```
Let's first create the `pacakge.json` file:
```console
npm init -y
npm i --save-dev electron
```
If you don't understand the previous commands, let me go through them right now. The first command, `npm init -y`, creates the `package.json` file, which stores the info of your NodeJS project, and we'll use commands which are stored in the file later on. The second command, `npm i --save-dev electron`, installs electron and saves it as a developer dependency. This means that we use the package to develop our project, but it isn't needed to be installed by the user.

Now that we have set up the `package.json` file, let's create the `main.js`. The `main.js` is the file which tells electron what to do. Put the following code into it:
``` javascript
const { app, BrowserWindow } = require('electron')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
```
Let's go through it. 
 - First, we import the `BrowserWindow` and `app` modules of the electron package.
 - We now create a function to create a browser window and define the details of the window such as the width and height of the window. We load the `index.html` file as the body of the window.
- We then create the window once Electron is initialized. 
- When all the windows are closed, we quit the application since the application should no longer be running.
- We then check whether to create a new window, which we do only if no browser windows are visible.

Okay, the hard part is done, let's get to the `index.html` file. This is where we'll create the body of our function. There's nothing really special about this, so just put in any `HTML` that you want in it and then you're good. To test, you could put in the following:
```HTML
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Hello there! Hello World!</title>
    </head>
    <body>
        Hello World!
    </body>
</html>
```
Now, go back to the `package.json` and we're going to modify it a little. It should look something like:
```JSON
{
  "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"
}
```
Change it to:
```JSON
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
```
This now changes 2 things:
 - We changed the main script to `main.js`
 - We added a start script and removed the test script, so now when we run `npm start`, it will run our app.

We've done it! Open up your console and type `npm start`, and you're app should be up and running!

Now that we've covered creating a basic electron app, we can move on to more complex things such as testing, adding a custom menu, keyboard shortcuts, notifications, multiple windows, and even detecting wether the user is offline or online! We'll cover all of this in the next article of the series, so stay tuned!