ElectronJS - Learn to Install & Adopt The All-New Eclectic Platform

ElectronJS - Learn to Install & Adopt The All-New Eclectic Platform

Amidst all those trends that are trending, the technological trend is something one should not turn a blind eye to. We mean, it works wonders for you to go for a digital detox, every once in a while. But your business definitely can not afford any such detox. Especially in these times of globalisation, when all the businesses’ marketplace is internet and competitors exist in almost every corner of the world. No, we do not mean to scare you. Rather, we are to guide you with our share of experience & expertise, spanning over 7+ years & 450+ international projects. 

Speaking of technological trends, the desktop application is definitely going like hotcakes. And amongst all the desktop app frameworks, ElectronJS seems to be acing the race. WebTorrent, WordPress, in fact even your Whatsapp, uses the desktop application built using ElectronJS. And from our experience & analysis, as a technical team, we have also agreed upon a host of technical benefits that they boast about it. Let us throw some more light on it: 

What is ElectronJS?
ElectronJS - A Desktop Application Development Framework engineered by Cheng Zhao - an engineer at GitHub. A platform that is flexible in its user interface and highly efficient in its performance, ElectronJS works across platforms viz. Mac, Linux, Windows, et al. ElectronJS, basically, creates native applications with web technologies like JavaScript, HTML, and CSS. Some of the most tedious processes of creating a desktop application are taken care of by ElectronJSJS and hence, simplifying your job as a user! 

Plus, you know can trust & should go for ElectronJS when the top-notch businesses, around the globe, has already chosen it for their desktop app. And yet, if you still have some queries regarding it, feel free to reach out to us and we’ll be obliged to address each of your queries to your satisfaction. Till then, let us guide you through the installation process of ElectronJS with Webpack. 

 

Install ElectronJS with Webpack

ElectronJS - Learn to Install & Adopt The All-New Eclectic Platform

Webpack, an open-source JavaScript module bundler, is taken into use for installing ElectronJS. Below we share the steps for this installation, along with the in-depth instruction to implement them: 
 

Steps 1 and 2:

Both the initial steps are self-explanatory & simple. So, let us jump straight on to the steps that demand explanation & guidance. 
 

Step 3: [main.js]


'use strict'

// Import parts of ElectronJS to use
const { app, BrowserWindow,  Tray, Menu, MenuItem } = require('ElectronJS')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let tray;
var force_quit = false;

// Keep a reference for dev mode
let dev = false

if (process.defaultApp || /[\\/]ElectronJS-prebuilt[\\/]/.test(process.execPath) || /[\\/]ElectronJS[\\/]/.test(process.execPath)) {
  dev = true
}

// Temporary fix broken high-dpi scale factor on Windows (125% scaling)
// info: https://github.com/ElectronJS/ElectronJS/issues/9691
if (process.platform === 'win32') {
  app.commandLine.appendSwitch('high-dpi-support', 'true')
  app.commandLine.appendSwitch('force-device-scale-factor', '1')
}

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    minWidth: 1024,
    minHeight: 768,
    show: false,
    webPreferences: {
      nodeIntegration: true
    },
  })

  // and load the index.html of the app.
  let indexPath

  if (dev && process.argv.indexOf('--noDevServer') === -1) {
    indexPath = url.format({
      protocol: 'http:',
      host: 'localhost:8080',
      pathname: 'index.html',
      slashes: true
    })
  } else {
    indexPath = url.format({
      protocol: 'file:',
      pathname: path.join(__dirname, 'build', 'index.html'),
      slashes: true
    })
  }

  mainWindow.loadURL(indexPath);






  tray = new Tray(path.join(__dirname, 'tray.png'));

  tray.setContextMenu(Menu.buildFromTemplate([
    {
      label: 'Show App', click: function () {
        mainWindow.show();
      }
    },
    {
      label: 'Quit', click: function () {
        force_quit = true;
        app.quit();
      }
    }
  ]));

  // Don't show until we are ready and loaded
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
    // Open the DevTools automatically if developing
    if (dev) {
      mainWindow.webContents.openDevTools()
    }
  })

  mainWindow.on('close', function(e){
    if(!force_quit){
        e.preventDefault();
        mainWindow.hide();
    }
});

  // Emitted when the window is closed.
  mainWindow.on('closed', function(event) {
    // 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
  })
}








//Menu creation

const template = [
  {
     label: 'View',
     submenu: [
        {
           role: 'resetzoom'
        },
        {
           role: 'zoomin'
        },
        {
           role: 'zoomout'
        },
        {
           type: 'separator'
        },
        {
           role: 'togglefullscreen'
        }
     ]
  },
  
  {
     role: 'window',
     submenu: [
        {
           role: 'minimize'
        },
        {
           role: 'close'
        }
     ]
  },
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
// This method will be called when ElectronJS has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)





// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  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 (mainWindow === null) {
    createWindow()
  }
})


 

Step 4: [webpack.config.js]

const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { spawn } = require('child_process')

module.exports = {
  entry: path.join(__dirname,'src','index.js'),
  output: {
    path: path.join(__dirname,'build'),
    filename: 'index.bundle.js'
  },
  mode: process.env.NODE_ENV || 'development',
  resolve: {
    modules: [path.resolve(__dirname,'src'),'node_modules']
  },
  target: 'ElectronJS-renderer',
  plugins: [
    new HtmlWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],
  devtool: 'cheap-source-map',
  devServer: {
    contentBase: path.resolve(__dirname, 'build'),
    stats: {
      colors: true,
      chunks: false,
      children: false
    },
    before() {
      spawn(
        'ElectronJS',
        ['.'],
        { shell: true, env: process.env, stdio: 'inherit' }
      )
      .on('close', code => process.exit(0))
      .on('error', spawnError => console.error(spawnError))
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname,'src','index.html')
    })
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.(css|scss)$/,
        use: [
          "style-loader",
          "css-loader",
          "sass-loader"
        ]
      },
      {
        test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
        loaders: ["file-loader"]
      }
    ]
  }
};

 

Step 5 and step 6: [package.json]


{
  "name": "App name",
  "version": "1.0.0",
  "productName":"App name",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "babel-node ./node_modules/webpack/bin/webpack --mode production",
    "start": "babel-node ./node_modules/webpack-dev-server/bin/webpack-dev-server --hot --host 0.0.0.0 --mode development",
    "prod": "babel-node ./node_modules/webpack/bin/webpack --mode production --config webpack.build.config.js && ElectronJS --noDevServer .",
    "build": "babel-node ./node_modules/webpack/bin/webpack --config webpack.build.config.js --mode production",
   },
  "devDependencies": {
    "@babel/core": "7.1.2",
    "@babel/node": "7.0.0",
    "@babel/plugin-proposal-class-properties": "7.1.0",
    "@babel/preset-env": "7.1.0",
    "@babel/preset-react": "7.0.0",
    "babel-loader": "8.0.4",
    "babili-webpack-plugin": "^0.1.2",
    "css-loader": "1.0.0",
    "ElectronJS-packager": "^13.1.1",
    "file-loader": "2.0.0",
    "html-webpack-plugin": "3.2.0",
    "mini-css-extract-plugin": "^0.7.0",
    "node-sass": "4.9.3",
    "npm-run-all": "^4.1.5",
    "path": "0.12.7",
    "postcss-cssnext": "^3.1.0",
    "postcss-import": "^12.0.1",
    "postcss-loader": "^3.0.0",
    "postcss-nested": "^4.1.2",
    "postcss-pxtorem": "^4.0.1",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.0",
    "webpack": "4.20.2",
    "webpack-cli": "3.1.2",
    "webpack-dev-server": "3.1.9"
  },
  "dependencies": {
    "ElectronJS": "^5.0.2",
    "react": "16.5.2",
    "react-dom": "16.5.2",
    "react-router-dom": "4.3.1",
  }
}

 

Step 7 : .babelrc


{
  "presets": [
    "@babel/env",
    "@babel/react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

 

Step 8 : Run Project

$ npm start

 

Builds Preparation Process for ElectronJS:

ElectronJS - Learn to Install & Adopt The All-New Eclectic Platform

Once the installation is done, you can now move forward to the process of Builds Preparation. Let us guide you with this process too! 

1. Install ElectronJS Packager


# for use in npm scripts
npm install ElectronJS-packager --save-dev

# for use from cli
npm install ElectronJS-packager -g

 

2. Setting Product Name & ElectronJS Version

npm install --save-dev ElectronJS

 

Package.json


{
 "name": "my-ElectronJS-app",
 "productName": "The ElectronJS app",
 "version": "0.1.0",
 "main": "main.js",
 "devDependencies": {
 "ElectronJS": "^1.4.3",
 "ElectronJS-packager": "^8.1.0"
 }

 

3. Building MacOS, Windows and Linux Package from the Terminal

For MacOS:

Now you can run this command from the terminal to build a package for mac:


ElectronJS-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds

 

For Windows:


ElectronJS-packager . my-ElectronJS-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName="The ElectronJS app"

 

For Linux:


ElectronJS-packager . my-ElectronJS-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds

 

overwrite: replaces any existing output directory when packaging.

platform: The target platform to build for.

arch: The architecture to build for.

icon: Sets the icon for the app.

prune: Runs npm prune –production before packaging the app. It removes unnecessary packages.

out: The name of the directory where the packages are created.
 

4. Using Command (Shortcut):

To make it easier to create new builds we can create scripts in package.json so that we don’t have to remember all these settings. Add the scripts below, making your package.json look like this:


{
 "name": "my-ElectronJS-app",
 "productName": "The ElectronJS app",
 "version": "0.1.0",
 "main": "main.js",
 "devDependencies": {
 "ElectronJS": "^1.4.3",
 "ElectronJS-packager": "^8.1.0"
 },
 "scripts": {
 "package-mac": "ElectronJS-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds",
"package-win": "ElectronJS-packager . my-ElectronJS-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"The ElectronJS app\"",    
"package-linux": "ElectronJS-packager . my-ElectronJS-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds"
 }

 

Now you can prepare the build using:

npm run package-mac

 

npm run package-win

 

npm run package-linux

 

Concluding Words:

Like every new innovation or idea, new technology also comes surrounded by a host of scepticism. But as time goes by, one witnesses the beneficial outcomes of it and gradually shuns the scepticism & adopts the respective technology. ElectronJS has already been through that phase of scepticism & is now in the blooming stage of acceptance. If you still haven’t thought about adopting it for your business, you’re definitely running late of technological times. So, buckle-up now and embrace the technology that is here to benefit you! 

To learn more about it or inquire how well can it work for you, get in touch with our ElectronJS team now!