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:
- Watch for changes in the
src
folder. When that happens, - Call
npm run build:development
, which will in turn runlwc-services build
and deploy binaries todist
- Have Electron watch changes in the
dist
folder so it can reload itself.
So let's get to it.
- First acquire the NPM package electron-reload. From the root of your project, do:
> npm install electron-reload
- 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'),
});
- 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
};
- Install fswatch, which is a cross-platform command-line tool that monitors a folder and outputs the changes the
stdout
.
> brew install fswatch
- 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
- Run Electron
npm run start
- 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 enablednoclear
, 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 | |
---|---|
macOS | 10.15.6 |
npm | 6.14.8 |
node | 14.10.0 |
electron | 10.1.1 |
electron-reload | 1.5.0 |
lwc-services | 2.1.6 |
fswatch | 1.15.0 |