A Beginner Guide to Create an Electron Application – Electron Tutorial

By | October 11, 2020

In this tutorial, we will introduce you how to create an electron application step by step, you can start to learn how to create your own electron application.

Preliminary

You should have installed electron using node.js first.

Here is an tutorial:

Install Electron in Node.js – A Step Guide – Electron Tutorial

We will start to creat an electron application.

Suppose we will create an application in path: F:\AI-Documents\app

Open your powershell and run npm init in F:\AI-Documents\app

npm init

You will get this result.

the electron app package.json test

Enter your package name, version, entry point, test command.

Notice:

test comman must be the electron, not electrontest or others.

You can eidt pacakge.json file to:

modify electron application package.json test command

A package.json file will be created in F:\AI-Documents\app

create an electron application package.json file

Create index.js file

The entry point file is index.js, which means we will run index.js file to start electron application.

We will create this file and add content below:

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

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

  // load window file index.html
  win.loadFile('index.html')
}

app.whenReady().then(createWindow)

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

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

In this file, app will manage the life cycle of electron application. BrowserWindow will create a window.

We can use BrowserWindow.loadFile() to load a html as the window of electron application. In this example, index.html is the window file.

Create window file index.html

index.html can be created using html, css or javascript.

Here is an example code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>This ia an electron application test.</p>
  </body>
</html>

Start electron application

You can run command below to start an electron application in F:\AI-Documents\app

npm test index.js

start an electron application using npm

Here index.js is the entry point file of this application.

The we will see a window.

electron application example and tutorial

Leave a Reply