In the Electron App that we develop at our company, there is no Webpack configured for bundling the App, since the App is just a shell to render a Web App. Moreover, the Electron code base isn't that big to deserve a sophisticated bundler, the Web App within is already CRA with typescript.
However, we are losing the benefit of having the default support of dotEnv supported by Webpack bundler, as well as hot reload and other cool features. Since CRA already hot reload the web contents, is not that big of a deal for Electron to have hot reload since it is just a frame. Then, ENV compilation becomes a major problem when we don't bundle the codes with the respective env
for electron-builder
to build.
Electron-builder is a packager that package the code, it does not compile your env file for you. Thus, your env inside the codes will become undefined
in the packaged build if we skip the bundling process. not cool :(
While not using Webpack or other bundling tool, we created a json file to host the env that we need and update them during CI/CD process. That way, we can just inject ENV that are set in the CI/CD tool into the json dynamically according to build pipeline.
First, create a config.json
file that stores the list of env that you want to update during build. It should default to dev environment variable so that you do not need to update them every-time during development. For example,
{
"env": "development",
"appUrl": "http://localhost:8080/",
"bugsnagAppId": ""
}
In your code,
// main.js
const fs = require('fs');
const config = JSON.parse(fs.readFileSync(path.join(__dirname, './build/config.json'), 'utf8'));
const isDevelopment = config.env === 'development';
if (isDevelopment) window.loadUrl(config.appUrl);
Then, set up your ENV in your CI/CD tool, you may have staging build pipeline and production build pipeline that has its own set of ENV. Once all is set, we use json
library to do the key-value update accordingly. Below is the script that we execute during CI/CD.
# build-script.sh
yarn install
json -I -f build/config.json -e "this.env='$(echo $NODE_ENV)'"
json -I -f build/config.json -e "this.appUrl='$(echo $APP_URL)'"
json -I -f build/config.json -e "this.bugsnagAppId='$(echo $BUGSNAG_APPID)'"
yarn build:mac
- Remember to add the library https://github.com/trentm/json to your package.json for it to work :)
Now, you have a dynamic config.json in different build of your Electron App.
Top comments (0)