Getting started with Electron

Let’s start by installing the latest version of electron using

  • npm i -D electron@latest

The Writing Your First Electron App goes through the process of setting up your first electron application, I’ll recreate some of these steps below…

  • Create a folder, mine’s test1
  • Run npm init, when asked for the entry point type main.js instead of index.js
  • Add main.js
  • Add index.html
  • Run npm install –save-dev electron
  • Add scripts section to package.json, i.e.
    "scripts": {
      "start": "electron ."
    }
    

Next up let’s add the following to the main.js file

const electron = require('electron');

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

function createWindow () {
  // Create the browser window.
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  win.loadFile('index.html')
}

app.on('ready', createWindow)

As you can see, we require electron, along with the app object and BrowserWindow. Next we create a BrowserWindow and load the index.html into it, so let’s supply something for it to load.

Change the index.html to the following

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

This demonstrates HTML content as well as using JavaScript within it.

Now run npm start and view your first electron application.