There are several ways to set Node environment variables in Electron, and the choice depends on the specific application requirements and development environment. Here are several common methods for setting and using Node environment variables:
1. Setting Environment Variables When Launching Electron
When launching the Electron application from the command line, you can directly set environment variables. For example, on Windows systems, you can use the following command:
bashset NODE_ENV=production && electron .
On macOS or Linux systems, the command is:
bashNODE_ENV=production electron .
This method is suitable for temporary modifications or quickly testing different environment configurations during development.
2. Dynamically Setting Environment Variables in the Main Process
In the Electron main process main.js file, you can use the Node.js process.env object to set environment variables. For example:
javascriptprocess.env.NODE_ENV = 'production'; const { app, BrowserWindow } = require('electron'); app.on('ready', () => { let mainWindow = new BrowserWindow({ // Window configuration }); mainWindow.loadURL('http://example.com'); // Other code });
This method allows dynamically setting environment variables based on different conditions when the application starts.
3. Using .env Files
For complex applications requiring multiple environment variables, using .env files provides centralized configuration management. This requires leveraging a library like dotenv to load settings from .env files.
First, install dotenv:
bashnpm install dotenv
Then, create a .env file in the project root directory, for example:
shellNODE_ENV=production API_URL=http://example.com/api
Load this configuration in the main process:
javascriptrequire('dotenv').config(); const { app, BrowserWindow } = require('electron'); console.log(process.env.NODE_ENV); // Outputs 'production' console.log(process.env.API_URL); // Outputs 'http://example.com/api' app.on('ready', () => { let mainWindow = new BrowserWindow({ // Window configuration }); mainWindow.loadURL(process.env.API_URL); // Other code });
Using .env files simplifies managing and switching between different environment configurations, while also enhancing code clarity and maintainability.
Example Application Scenario
Suppose you are developing a desktop application for an e-commerce platform that connects to different API servers based on the environment (development, testing, production). You can control the server address by setting the API_URL environment variable and use .env files to manage these variables, enabling quick configuration switching across development stages to improve efficiency and stability.
These are several methods for setting Node environment variables in Electron. Choose the appropriate method based on your specific requirements to effectively manage environment variables.