Saturday, February 23, 2019

How to start Electron

Electron

Electron framework is used to make desktop application with Javascript and APIs.
Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs. You could see it as a variant of the Node.js runtime that is focused on desktop applications instead of web servers. -- Electron official site
If you already know how to write Javascript, Electron can be a nice choice to develop desktop applications. Official quick start is here.

At first

What I do here is exactly same as what the official tutorial does. Please note that this is just a memo of what I did.

Prerequisites

  • OS: Ubuntu 18.04.2 LTS

Create an app with Electron

Install necessary modules

At first, check if you have nodejs and npm.
$ nodejs -v
$ npm -v
If you don't have them, install them:
$ sudo apt install nodejs
$ sudo apt install npm

Create a .json file

Create a new folder and run npm init in the folder:
$ cd {YourNewFoldersPath}
$ npm init
You can make a package.json by the command. The content of the json file should be like this:
{
  "name": "test-app",
  "version": "0.0.1",
  "description": "test.",
  "main": "main.js"
}
Just add command to start the electron to change it an electron app:
{
  "name": "test-app",
  "version": "0.0.1",
  "description": "test.",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  }
}

Install electron

From the folder we made, run this command to install electron:
$ cd {YourNewFoldersPath}
$ npm install --save-dev electron 

Execute electron app

Create main.js in the same folder:
$ cd {YourNewFoldersPath}
$ touch ./main.js
Write as follows inside and save it:
const { app, BrowserWindow } = require('electron')

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

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

app.on('ready', createWindow)
Execute the app.
$ npm start
You can see that a simple browser running.

Read index.html

Create index.html in the same folder:
$ cd {YourNewFoldersPath}
$ touch ./index.html
Write as follows inside and save it:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </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>
Execute the app.
$ npm start
You can see that the browser reads the index.html: