This article will teach you how to read environment variables from .env files into multiple Angular environments.
What is the .env file?
The .env file is a plain-text file used to store sensitive data and environment-specific configuration for a software application. Sample file:
GREETING = HELLO WORLD SECRET = 12345
Enter fullscreen mode
Exit fullscreen mode
By default, Angular uses the Environment files built into the framework (under src/environments ), which are good for runtime but are publicly visible (and thus expose environment secrets). To get around this, we'll create a .env file for each environment (dev, staging, production) and load those variables into the Angular env file.
How are we going to implement this?
Create an .env file for each environment
Create a Node.js script that loads those .env files into memory
Use the script to override Angular environment project files with values from the .env files
Run the Angular build
This solution adds environment variables to the project…