Categories
Electron Tutorials

Writing your first app with Electron

This post is in continuation with the previous posts about creating desktop application using Electron app framework

I have covered Introduction in previous post.

Our Approach

We can get started with two approaches

  1. Bottom to top: With this approach we can start really from basics like words, sentence and paragraph and build up.
  2. Top to bottom: This approach starts with having some kind of project in mind.

I will mix both the approach as soon as we have enough basics (thanks to bottom to top approach) we will switch to Top to bottom approach and built our fist cross platform desktop app.

Get Started

In order to get started, we need package.json 

  1. Create a empty directory
  2. cd into the newly created directory
  3. Type npm init and go with the defaults

You will get following screen

This screen we see when we initialize the package.json file by typing npm init command in the console. Part of create desktop application using electron app framework technbuzz

Just hit Enter to continue or type anything as long as it starts with y.

Now package.json is created and look at the “main” property in you package.json file. This is the starting point for our electron app. You can stick to index.js but I would rename it to main.js as this makes much sense.

Let’s write to our index.js

console.log('Hello World');

  Let’s run our app. But we need to install electron

npm install electron

This will add electron as a local package. We can also install it globally by adding -g flag. Here is why you need local version.

Now just type electron . and we see following output in our console

We are consoling log Hello World in attempt to create first desktop application Technbuzz

Congrats!  you have build your first app. It lives in the console. Continue reading if you want to add it an awesome UI.

Adding Interface

For UI we need to tell electron to load HTML file.

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

app.on('ready', () => {
  const mainWindow = new BrowserWindow();
  
  mainWindow.loadURL(`file://${__dirname}/index.html`);
});

On line 1 I’m using destructuring assignment which saves a lot of keystroke. Otherwise it can be written as 

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.app;

On line 3 we wait for ready event, and on line 4 we use BrowserWindow (which creates and modifies browser windows)  to create a new browser window. On line 6 we are are loading index.html.

Now we can use the index.html as your usual website development. We can use CSS to style our app. 

Let’s create a basic index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Electron App</title>
</head>
<body>
  <h1>Hello</h1>
  <p>I just wrote my first Electron Application</p>
</body>
</html>

Go back to console and press Ctrl+C to close any running version of our app and run it again using electron . 

This is the output with Graphical User interface of our first desktop application using Electron Technbuzz
This is our First Desktop Application and it’s a browser window

We can also go to Dev Tools just like we have in the chrome either from View > Toggle Developer Tools  or pressing Ctrl+Shift+I

This

Now with User Interface to our application look much better than the console version. There is one important aspect of using Electron to create desktop application that we will cover next.

  Two Processes of Electron

Basically Electron has two environments. One responsible of speaking to the operating system. Handles all the system level operations (file system etc) and this is called Main Process. Second one is called Renderer Process or we can call it a browser. From here we can script our Browser Level application.

Adding Renderer process is just like attaching a script tag to your website. Let’s modify our index.html

<body>
  <h1>Hello</h1>
  <p>I just wrote my first Electron Application</p>
  <script src="script.js"></script>
</body>

For brevity let’s just log the browser in our script.js

console.log('This is Renderer Process')

Now In order to test our code you can either restart our Electron from terminal or just reload the browser from View > Reload or pressing Ctrl+R (This makes debugging of electron app so easy)

This figure shows how renderer process of Electron app framework looks. This is an attempt of building cross platform app on Technbuzz

Refactoring the Code

We do want to apply some good practices to our main.js Right now we can see a flash of white screen than our app. If this is not noticeable go ahead give your app a black interface and then you can see the flash of white followed by black interface. For illustration I will modify the index.html by adding following style block

<title>Electron App</title>
  <style>
    body{
      background-color: #000;
      color: #fff;
    }
  </style>

Solution for Flash of White Screen

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

let mainWindow = null;

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 300,
    height: 600,
    show: false
  });

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  mainWindow.loadURL(`file://${__dirname}/index.html`);
});

From line 5-9 we are giving configuration object to browser window. I accept many options. To cope with White screen we hide the window initially and show it later on line 12-14

We have also refactored the code. As variables are function scoped that’s why it’s moved the mainWidow in to the global due to garbage collection.

Conclusion

We have made quite progress with Electron.  I will continue with one more real life example in the next article to uncover other aspects of Electron app framework.


[1] Apps that are build with older version of electron might cause an issue when they are compiled with newer global version of electron. Becuase of change in the API

One reply on “Writing your first app with Electron”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.