Last Updated: 4/23/2022 Created: 9/11/2020

How to Hot-Reload your LWC-based Electron App

If you've created your Lightning Web Components app using create-lwc-app, your package.json already has the ability to hot reload (AKA live reload) any changes you make to the source. This functionality, initiated by npm run watch only works when you're using the provided localhost web server. It doesn't work for Electron.

What we want is to have lwc-services build the project so that the artifacts are deployed to the local dist folder where Electron is sourcing them from. Here are the steps:

  1. Watch for changes in the src folder. When that happens,
  2. Call npm run build:development, which will in turn run lwc-services build and deploy binaries to dist
  3. Have Electron watch changes in the dist folder so it can reload itself.

So let's get to it.

  1. First acquire the NPM package electron-reload. From the root of your project, do:
> npm install electron-reload
  1. In scripts/main.js, add the following near the top of the file:
const distPath = path.join(__dirname, '..', 'dist');

require("electron-reload")(distPath, {
    electron: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'),
});
  1. In lwc-services.config.js, set noclear to true. With this, lwc-services will overwrite files as opposed to deleting them first.
module.exports = {
    resources: [{ from: 'src/resources/', to: 'dist/resources/' }],
    noclear: true
};
  1. Install fswatch, which is a cross-platform command-line tool that monitors a folder and outputs the changes the stdout.
> brew install fswatch
  1. In a separate terminal window, in the root project folder, run the following:
> fswatch src | while read; do npm run build:development </dev/null; done
  1. Run Electron
npm run start 
  1. In your code editor, make a change to the file. After a few seconds, the app should reflect the changes.

Troubleshooting:

If something doesn't work right, here's a few things to look at:

  • Ensure that the paths are correct in main.js
  • Check the scripts in package.json
  • Make sure that when you make a change, lwc-services rebuilds the code, and that the dist folder is updated. Since we enabled noclear, some types of changes (e.g. file deletions) will not take affect until a clean build, so keep that in mind.
  • See if any chokidar options will help. (Electron-reloader accepts the same properties in the object passed as the second argument in the require line). For example, awaitWriteFinish option allows to override defaults.

And for reference, here's my environment:

version
macOS10.15.6
npm6.14.8
node14.10.0
electron10.1.1
electron-reload1.5.0
lwc-services2.1.6
fswatch1.15.0