Open In App

Hot Reload in ElectronJS | Set – 2

Last Updated : 19 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

This article is a continuation of the Hot Reload in ElectronJS. In the previous article, we have discussed what is Hot Reload/Live Reload and how do we implement it in an Electron application using the electron-reload and the electron-reloader npm packages respectively. In this article, we will implement Hot Reload within the Electron application using the elemon and the electron-hot-reload npm packages respectively. Also, as mentioned in the previous article, Hot Reload functionality should only be implemented in the Development environment. Hence, we have used the NODE_ENV Environment variable to define the same as used in the previous article. We can access this variable using the global process object in Electron. 

We can also set this Environment Variable from the Windows console. For more detailed information on the Environment Variables supported and used in Electron.

In case, we want a solution for the development staging environment which is supported on all OS platforms and does not require any configuration changes, we can also refer to the article: Manage Staging Environments in ElectronJS. We will continue using the same code base from where we left off in the previous article. The project structure and the package.json file also remain the same. We will now implement the Hot Reload functionality using the elemon and the electron-hot-reload npm packages respectively. 

  • First, we will install elemon using npm
npm install elemon --save
  • Install electron-hot-reload using npm
npm install electron-hot-reload --save

Both of these packages are completely unrelated and have different syntax and use different methods. We can implement Hot Reload functionality using both of these packages separately in Electron. The basic steps required to set up the Electron application remain the same. 

package.json: 

{
  "name": "electron-hot",
  "version": "1.0.0",
  "description": "Hot Reload for Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.2.5",
    "electron-hot-reload": "^0.1.4",
    "elemon": "^5.0.3"
  },
  "devDependencies": {
    "electron-reload": "^1.5.0",
    "electron-reloader": "^1.0.1"
  }
}

Output: 

Note: Refer to the previous article for a thorough understanding of the NODE_ENV environment variable. 

  • Approach 1: Using elemon npm package. The elemon is a light-weight module that provides a simple and efficient way to add Hot Reload functionality when developing Electron applications. Also, this package can only be used after the ready event of the app module is emitted in the Main Process of the application. According to the authors and contributors of this package, the code is compliant with Standard JS which defines a certain set of rules that need to be followed when coding in JavaScript. When implementing Hot Reload in Electron using this package, if there is any change in any of the Renderer Processes the respective BrowserWindow Instance is reloaded but when there is a change in the Main Process of the application i.e. the main.js file, the application Exits the current instance and relaunches with a new Instance to reflect the changes. 
  • For more detailed information, refer to the link: This package is compliant and works without any errors as of Electron v8.3.0 and it is regularly updated. 

https://www.npmjs.com/package/elemon. 

  • main.js: Add the following snippet in that file. We will be adding this code snippet to the createWindow() function. 

javascript




const env = process.env.NODE_ENV || 'development';
// ..
    // Open the DevTools.
    win.webContents.openDevTools()
  
    if (env === 'development') {
        const elemon = require('elemon')
        elemon({
            app: app,
            mainFile: 'main.js',
            bws: [
                // The BrowserWindow Instance used 
                // in the createWindow() function is win. 
                { bw: win, res: ['index.html'] },
            ]
        });
    }


  • Explanation: The elemon(refs) Instance method takes in the following parameters. This method does not have any return type. All parameters passed in this Instance method are required.
    • refs: Object This object takes references to the app Instance, the BrowserWindow Instances, the Main Process file, and the respective Renderer Process files and Instances. It takes in the following parameters.
      • app: Object This parameter takes in an object which represents the Instance of the main app module which is imported at the starting of the main.js file.
      • mainFile: String This parameter takes in a String that represents the Main Process file name. In this case, it is the main.js file.
      • bws: Object[] This parameter takes in an array of objects, with each object representing the respective BrowserWindow Instance and its associated files and resources. If there are multiple BrowserWindow Instances defined within the Main Process of the application, then each BrowserWindow Instance will be represented as a separate object within the array. Every bws object takes in the following parameters.
        • bw: Object This parameter represents the global BrowserWindow Instance.
        • res: String[] This parameter represents an Array of Strings where every String represents a resource or the name of the file which is somehow connected to that BrowserWindow Instance. In our case, this parameter will consist of the index.html as the only String element within the res Array. Refer to the code for better understanding.
  • Approach 2: Using electron-hot-reload npm package. The electron-hot-reload is also a light-weight module that provides a simple way to add Hot Reload functionality when developing Electron applications. Also, this package can only be used after the ready event of the app module is emitted in the Main Process of the application. This package is not as popular as elemon but it provides a different set of features than the other packages. The most crucial feature of this package is that it provides separate watchers for the Main Process and the different Renderer Processes of the application, therefore, making it more customizable for each of the Processes. We can also specify hooks before Hot Reloading takes place for the files, and we can directly specify the name of the files for which we want Hot Reloading. This package also provides the additional advantage of catching Unhandled Errors in the application, if we specify so. 
  • For more detailed information, refer to the link: The behaviour of this package is the same as that of elemon. In changes to the Main Process, the application is restarted and in changes to the Renderer Process, the respective BrowserWindow Instance is reloaded. This package is compliant and works without any errors as of Electron v8.3.0 and but it is not regularly updated. 

https://www.npmjs.com/package/electron-hot-reload. 

  • main.js: Add the following snippet in that file. We will be adding this code snippet at the end of the file without touching any existing code. 

javascript




// Importing the watchers from electron-hot-reload
const { mainReloader, rendererReloader } = require('electron-hot-reload')
const env = process.env.NODE_ENV || 'development';
// ..
if (env === 'development') {
    const mainFile = path.join(__dirname, 'main.js');
    const rendererFile = path.join(__dirname, 'index.html');
      
    mainReloader(mainFile, (error, path) => {
        console.log(path);
        console.log("It is a main's process hook!");
    });
      
    rendererReloader(rendererFile, (error, path) => {
        console.log(path);
        console.log("It is a renderer's process hook!");
    });
}


  • Explanation: Both the mainReloader( paths, ignored, handler, options ) Instance method and the rendererReloader( paths, ignored, handler, options ) Instance methods have the same method signature. Both of these Instance methods take in the following parameters. Both of these methods do not have any return type.
    • paths: String/String[] This parameter takes in a String parameter or an Array of Strings representing the path of the files to be watched for Hot Reloading. We need to specify the full path of the file and hence we have used the path.join() method of the NodeJS path module. In this tutorial, we have specified the path to the main.js file and the index.html respectively for the Main Process and the Renderer Process watchers.
    • ignored: RegExp/RegExp[] (Optional) This parameter is an Optional parameter. This parameter takes in a RegExp parameter or an Array of RegExp representing the Regex Expressions of the files and directories to be ignored for Hot Reloading. For more detailed information on the RegExp, Refer to the article: JavaScript RegExp [abc] Expression. For understanding how Regular Expressions work in JavaScript, Refer to the article: JavaScript Regular Expressions.
    • handler: Function (Optional) This function is Optional. This function is a callback function to create hooks and catch unhandled Errors within the application as mentioned in the description. This function receives two parameters:
      • error The Unhandled Error.
      • path The path of the file changed.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads