When using Electron Builder to package Electron applications, it is often necessary to configure the packaging parameters. Electron Builder supports multiple configuration methods, one of which is configuring via a YAML file. If you need to manage environment variables using .env files during this configuration process, it can be achieved through several steps.
Step 1: Install the necessary packages
First, ensure that you have installed the dotenv package. This package helps load environment variables from .env files in the Node.js environment.
bashnpm install dotenv
Step 2: Load the .env file
In your Electron main process code or at the beginning of your packaging script, use the following code to load the .env file:
javascriptrequire('dotenv').config();
This line of code automatically reads the .env file from the project root directory and loads its contents into process.env. If your .env file is located at a different path, you can specify the path using the config function's parameters:
javascriptrequire('dotenv').config({ path: '/full/custom/path/to/your/env/vars' });
Step 3: Use environment variables in the YAML configuration file
In the electron-builder.yml configuration file, you can directly reference environment variables using the ${env.VARIABLE_NAME} syntax. For example, if you want to set the build output directory and the information is stored in the .env file under BUILD_OUTPUT_DIR, you can write:
yamldirectories: output: "${env.BUILD_OUTPUT_DIR}"
Example
Assume your .env file contains the following:
shellBUILD_OUTPUT_DIR=build API_KEY=123456
You can use them in the electron-builder.yml file as follows:
yamldirectories: output: "${env.BUILD_OUTPUT_DIR}" extraMetadata: main: "main.js" name: "YourAppName" APIKey: "${env.API_KEY}"
After this configuration, when Electron Builder runs, it will parse the variables from the .env file and replace the corresponding placeholders in the YAML file.
Important Notes
- Ensure that you do not call any code that depends on these environment variables before loading the
.envfile. - For highly sensitive environment variables (such as API keys), ensure that the
.envfile is not exposed in public code repositories.
By using this method, you can effectively integrate dotenv with Electron Builder, making environment configuration more flexible and secure.