DEV Community

Cover image for Announcing @ngx-env/builder
Chihab Otmani
Chihab Otmani

Posted on • Updated on

Announcing @ngx-env/builder

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Define Environment Variables in .env

NG_APP_ENABLE_ANALYTICS=false
NG_APP_VERSION=$npm_package_version
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
<!-- Same output -->
<span> {{ 'process.env.NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ 'NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ branch }} </span>
Enter fullscreen mode Exit fullscreen mode
<!-- index.html -->
<head>
  <title>NgApp on %NG_APP_BRANCH_NAME%</title>
</head>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Variables defined in .env file or in the command line are injected into your Angular Application.

Links

Top comments (2)

Collapse
 
mmannefeld profile image
Michael Mannefeld

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...)

Collapse
 
spock123 profile image
Lars Rye Jeppesen

Great stuff, thanks