How to set up hot reload in Electron

Hot Reloading is a beloved feature of developers. It allows changes in source code to be instantly reflected in the output/browser without restarting the application. Electron does not provide any built-in hot reloading module.

However, Electron can still use this hot reloading feature via using 3rd-party libraries. In this post, we will implement Hot Reload in Electron app using electron-reloader package.

Install

npm install electron-reload --save-dev

Add the package to dependencies in package.json.

"dependencies": {
    "electron-reload": "^1.5.0"
 }

We can force the whole app to reload by add these lines to main.js.

require('electron-reload')(__dirname, {  
  electron: require(`${__dirname}/node_modules/electron`)
});

main.js file with other codes

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const electron = require('electron')
const path = require('path')


require('electron-reload')(__dirname, {  
  electron: require(`${__dirname}/node_modules/electron`)
});


function createWindow () {
  // Create the browser window.
  const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
  const mainWindow = new BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  })

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

  // Open the DevTools.
   mainWindow.webContents.openDevTools()
}

// 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.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    // 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
    
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close