Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use process.env in Angular 5 environment

I try to build an Angular 5 application with the standard ng build --prod command, and I want to set the basic API-Url in the environment.prod.ts to a value dependent on my process.env variables.

This is my file:

export const environment = {     production: true,     apiUrl: `${process.env.BASE_URL}` || 'http://localhost:8070/', }; 

But when I try to build the application the following error occurs:

ERROR in src/environments/environment.ts(7,16): error TS2304: Cannot find name 'process'.

How can I set my API-Url according to an env variable when building the application?

like image 721
Freshchris Avatar asked Mar 26 '18 16:03

Freshchris


People also ask

Can we use process env in Angular?

Short answer, no. When we execute a CLI command, CLI being a Node. js application, has access to all the system environment variables through process. env , however CLI when building our application does not provide this information to it.

What is process env in Angular?

process. env is available to Node applications, which an Angular application is not. You have several options: Make a task of some sort in your build pipeline to update the environment file with the correct value if it truly needs to be dynamic.

Can Angular access environment variables?

Introduction. If you're building an app that uses an API, you'll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.


1 Answers

Update

Per the comments below the original answer was not entirely clear -- Angular is built with Angular CLI, which is a node application, but you aren't able to access process.env directly from within the app during that build process, as it's not processed as a Node application.

The concepts stay pretty much the same, but it's important to understand the above.

Original

You won't have access to process.env at compile-time of the Angular code.

process.env is available to Node applications, which an Angular application is not.

You have several options:

  1. Make a task of some sort in your build pipeline to update the environment file with the correct value if it truly needs to be dynamic.

  2. Just hardcode it and make several environmental files to match each of your environments. You can specify your environments in your angular-cli.json.

Option number 2 sounds like it might be right for you. In that case, you want to put this in your angular-cli.json:

"environments": {     "dev": "path/to/dev/env",     "prod": "path/to/prod/env" } 

and build your app with ng build --env=prod.

Here is more in-depth information: https://alligator.io/angular/environment-variables/

like image 67
chrispy Avatar answered Oct 08 '22 18:10

chrispy