How to set up hot reload on Electron

By

Learn how to set up hot reload in an Electron app with the electron-reloader module, so your window refreshes on every file change without restarting.

~~~

To set up hot reload in an Electron app, install the electron-reloader module and require it at the top of your main process file. From that point on, every time you save a file the app reloads by itself.

Why does this matter? Without it, the workflow is painful. You change a line of CSS, then you quit the app, then you run electron . again, and you wait for the window to show up. Multiply that by a hundred edits a day.

With npm module electron-reloader, the module watches your project files. When a renderer file changes (your HTML, CSS, or frontend JavaScript), it reloads the window. When the main process file changes, it restarts the whole app, because a window reload is not enough in that case.

The sample app

Suppose you have this sample Electron application:

index.js

const { app, BrowserWindow } = require('electron')

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

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

app.whenReady().then(createWindow)

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

How to enable hot reload

Install electron-reloader as a development dependency:

npm install -D electron-reloader

Then add this line to the index.js file:

try {
  require('electron-reloader')(module)
} catch (_) {}

Notice the try/catch block. It’s not decoration. You install the module as a dev dependency, so it does not exist in the packaged app your users run. Without the try/catch, the production build would crash on startup with a “module not found” error. The empty catch swallows that error, and the app runs normally.

Also notice we pass module to the function. The module uses it to figure out which file is the entry point of your app, so it knows what to watch.

That’s it. Now start the application using electron ., or npm start if you have

"start": "electron .",

in your package.json.

Change the <h1> text in index.html and save. The window updates right away. Change something in index.js and the whole app restarts. No manual quitting, no manual relaunching.

One pitfall I ran into: if nothing reloads, check that you added the require line to the main process file, the one listed in the main field of package.json. Adding it to a renderer script does nothing, because the watcher must run in the main process.

Tagged: Tools · All topics
~~~

Related posts about tools: