Building a Simple Hello World App in Electron

Electron is one of the most popular frameworks in building native desktop applications compatible for Windows, Linux and MacOS systems. We can start using Electron if we already know web development because Electron is also using HTML, CSS, and JS to build native desktop applications.

Here we are going to build a simple Hello World application using Electron.

STEPS

1. INSTALL ELECTRON

After successful installation of Node and NPM, Electron can be installed globally with the command below.

npm i electron -g

2. INITIALIZE THE PROJECT

First, create a project directory and a package.json file under it.

Now direct to the folder and make a package.json inside it.

mkdir AwesomeProject
cd /AwesomeProject
npm init

Enter the project details if you wish or skip.

3. CREATE A VIEW

Now create the file we wanted to be viewed when opening our app. Electron uses HTML to render the view and so we need to create an index.html file.

index.html

<html>
  <head>
    <title>Hello World Application</title>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

4. CREATE AN INDEX.JS FILE

In package.json, we programmed that the root file of our project is index.js. So we need to create it. Some points about the structure of this index file are listed below.

  • Import the components we need in our project
  • Create a new browser window.
  • Define the view it wants to show on loading the window(index.html).

index.js

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

function newApp() {
  win = new BrowserWindow();
  win.loadURL(
    url.format({
      pathname: "index.html",
      slashes: true
    })
  );
}

app.on("ready", newApp);

5. RUNNING OUR APPLICATION

Now we can run our Electron app using the command below.

electron .

Have a nice code !

Be the first to reply

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.