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
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 before build time. So the latest build has variables baked in.
This solution is suitable if:
- You're doing local development ✅
- You're hosting the application (dist files) yourself ✅
- You're building a Docker image (for any environment) ✅
It is not helpful if you need to add environment variables after the build (through some UI on AWS, GitHub, or elsewhere). ❌
You can grab the full code on this package to load environment variables from the selected .env file. This will generate the node_modules directory.
> npm i dotenv
Then create the index.js file in the scripts directory. This is where we'll write the script.
Finally, update the . If you're interested in learning how to Dockerize an Angular application, you can learn that here.
Bye for now 👋
SOCIAL SHARE CARD GENERATOR