Sunday, November 5, 2017

World's smallest electron app

Electron seems to be a very easy-to-setup system if you already have node.js and npm. I could get a small app running even on Windows. Here's what you do.

Create a project.json file

You can use 'npm init' for this, or just your text editor. The example I can give is

{
  "name": "electron1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "~1.7.8"
  }
}


Create an index.html file

This will be the default screen of the app. The example I can give is

<html>
  <body>
    <h1>Ha!</h1>
  </body>
</html>


Create a index.js file

This will be the code behind the app. The example I have is

var electron = require('electron')
var app = electron.app

var path = require('path')
var url = require('url')

let mainWindow


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

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
 
    // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)


Launch the app

There is a one-time command you need to execute:

npm install

After that is done you can launch your app using

npm start

Credits

This is nothing but a reduced version of the Electron quick-start app

No comments:

Post a Comment