DEV Community

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

Posted 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 sensitive data 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_NOT_SECRET_CODE will be exposed in your TS/JS as process.env.NG_APP_NOT_SECRET_CODE.

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

Discussion (1)

Collapse
spock123 profile image
Lars Rye Jeppesen

Great stuff, thanks