Have you ever wanted to consume variables declared in your environment inside your Angular application?
# GitHub Action command
NG_APP_GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} ng build
Environment variables can be useful for:
- displaying information conditionally based on where the project is deployed
- consuming data (potentially sensitive) that lives outside of version control
@ngx-env/builder
With @ngx-env/builder
the environment variables will be defined for you on process.env
, just like in Node.js applications.
For example, having an environment variable named NG_APP_API_BASE_URL
will be exposed in your TS/JS as process.env.NG_APP_API_BASE_URL
.
The environment variables are embedded during the build time.
Add @ngx-env to your CLI project
ng add @ngx-env/builder
Define Environment Variables in .env
NG_APP_ENABLE_ANALYTICS=false
NG_APP_VERSION=$npm_package_version
Use in TS and HTML
@Component({
selector: "app-footer",
})
export class FooterComponent {
version = process.env.NG_APP_VERSION;
branch = process.env.NG_APP_BRANCH_NAME;
token = process.env.NG_APP_GITHUB_TOKEN;
}
<!-- Same output -->
<span> {{ 'process.env.NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ 'NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ branch }} </span>
<!-- index.html -->
<head>
<title>NgApp on %NG_APP_BRANCH_NAME%</title>
</head>
Run your CLI commands
npm start
# Command Line environment variable
NG_APP_BRANCH_NAME=`git branch --show-current` NG_APP_GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} npm run build
Variables defined in .env
file or in the command line are injected into your Angular Application.
Links
- GitHub repository: https://github.com/chihab/ngx-env.
- Npm package: https://www.npmjs.com/package/@ngx-env/builder.
Top comments (2)
interesting approach, thank you very much.
I only had to use a different notation for Angular 13 because the compiler was complaining:
version = process.env['NG_APP_VERSION'];
instead of
version = process.env.NG_APP_VERSION;
Then it worked fine.
And i think, it would be worth mentioning that the variables need to start with 'NG_APP', as you did in your article (indepth.dev/tutorials/angular/inje...)
Great stuff, thanks