Electron w/ CRA
This quick start guide will show you how to add Electron into an existing app created with create-react-app. Some of these instructions are from this post. I've updated the instructions for Electron v12.0.0 and added some additional steps for usage.
Setup#
Install the following packages within your React app.
Add the following to public/electron.js
Add these lines to your package.json. Fill in the author and description fields.
Add these lines to the scripts section of your package.json
Run the following. It will add some dev-dependencies for building, a couple of scripts in package.json, and an Electron-Forge config in package.json.
This changes the start script in package.json. Within the scripts in package.json, change start, package, and make to the following:
Add /out to your .gitignore if it isn't already there.
In package.json there should be a config.forge.packagerConfig object. Add the following to packagerConfig.
Running in Dev Mode#
At this point you can run your app in Electron in dev mode with:
If you get an error saying 'electron' is not recognized as an internal or external command, you can try re-installing your node_modules. Unsure why this problem happens, but it may be a problem with Windows + VS Code + Git Bash.
Production Build#
To package your application so that it can be executed run:
Your built app should be in the out directory e.g. out/MY APP-win32-x64/MY APP.exe
Accessing the Filesystem in Electron#
If you want access to things like the filesystem from within your React code in CRA, you're going to have to do some extra work. Install the following package. This allows you to somewhat edit the webpack config without requiring you to eject.
Create craco.config.js at the root of your project and fill it with:
Change/add the following scripts in your package.json:
In your public/electron.js file, ensure that the BrowserWindow that gets created contains the following (specifically the webPreferences settings):
If you want to support both web and desktop versions and you want to distinguish whether you're running in Electron vs. the web at run-time so you can turn certain features off, install the following package.
You can now have a component that has access to things on the filesystem. Here's a list of paths available to you.
Next Steps#
- Custom Icons (docs here: https://dev.to/mandiwise/electron-apps-made-easy-with-create-react-app-and-electron-forge-560e)