About environment.ts in your Angular applications (2024)

About environment.ts in your Angular applications (1)

Environment.ts is a common place where you keep your application settings. Rather than hardcoding your settings in your components, pipe or any typescript files in Angular, having the application settings in the environment file will give you a great benefit in that you could have different settings in different application environments. Besides, all the application settings will be centralised in a file and easier to modify if needed.

The environment.ts is well documented in Angular documentation but it’s kept in another topic: Angular — Building and serving Angular apps. Hence, some people might not be aware of the environment.ts file’s usage.

This article is almost similar to the Angular official documentation. I just add additional information to this article to let you understand how to use the environment.tsbetter. This article might get outdated, so always refer to the official Angular documentation for the latest information: Building and serving Angular apps.

You will find a folder called environments in every Angular projects. This folder is where all the application settings are kept in environment specific. environment.ts is the default environment and this file will be referenced in your project.

yourProject/src/environments
- environment.ts
- environment.prod.ts

You might be wondering which environment.ts file to import cause you will find multiple files in the environments folder. To use the application settings, you just need to import the environment.ts file. I will explain why below.

import { environment } from './../environments/environment';

The snippet below shows the app.component.ts uses a variable from environment.ts file.

// app.component.ts
import { Component } from '@angular/core';
import { environment } from './../environments/environment';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
if(environment.production) { // 👈🏻👈🏻👈🏻
// some implementation if this is production environment
}
}
title = 'app works!';
}

You will find a preset variable productioneverytime you generate a new Angular application.

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
production: false // 👈🏻👈🏻👈🏻
};

Question: can we delete this variable? The answer is NO because this variable is used in the main.ts to enabled production mode if the production variable is set to true. When production mode is enabled, Angular will enhance the application performance by disabling verifies that a change detection pass does not result in additional changes to any bindings (also known as unidirectional data flow). I will not talk more about this method enableProdMode here. If you are interested about enableProdMode, you may read more about what enableProdMode does in this article: https://lukaonik.medium.com/what-is-the-difference-between-production-and-development-mode-in-angular-3eed82b9cf73. In other words, the production variable should be set to true whenever you are NOT debugging your application.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode(); // 👈🏻👈🏻👈🏻
}

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

Tips: Angular provides a utility function to check if the app is running in dev mode.

import { Component, OnInit, isDevMode } from '@angular/core';

@Component({ ... })
export class AppComponent implements OnInit {
ngOnInit() {
if (isDevMode()) { // 👈🏻👈🏻👈🏻
console.log('Development!');
} else {
console.log('Production!');
}
}
}

You can have one or more variables in the environment.ts file depending on your need. Let’s add a simple variable enableLogginginto environment.ts:

// environment.ts

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
production: false,
enableLogging: true
};

To use this newly added variable, you need to import the environment.ts file and use it in any typescript file in your Angular application.

// app.component.ts

import { Component } from '@angular/core';
import { environment } from './../environments/environment'; // 👈🏻👈🏻👈🏻

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
if(environment.enableLogging) { // 👈🏻👈🏻👈🏻
console.log('Angular app started');
}
}
title = 'app works!';
}

We normally will have multiple environments per application. The setup for the Angular application will differ from developer to developer. Nevertheless, you will need to configure the additional environments, if you wish to have more than just development and production environments.

By default, you will have environment.ts and environment.prod.ts in your Angular application. I use environment.ts as development environment. As I develop Angular application locally, I don’t need to add additional arguments to the command and environment.ts will be used as default settings. Whereas for production environment, you will need to pass additional parameter ng serve --configuration production.

Let’s configure a staging environment for the existing Angular application.

First of all, you need to add a new file to the environments folder. The naming convention of the file is environment.<environment_name>.ts. Let’s create a file called environment.staging.tswith the following content:

// environments/environment.staging.ts
export const environment = {
production: true // true if you are not debugging your application
};

Next, all the variables that are available in environment.ts, are required in this environment.staging.ts because the environment.staging.ts will replace environment.ts during compilation (ng serve or ng build). So, you need to make sure there are no missing variables in the environment.staging.ts file, or else the compilation will fail.

To be safe, you can copy the content in environment.ts to environment.staging.ts and then modify the settings inenvironment.staging.ts to the staging settings. Now we have done with the environment.staging.ts.

Extending angular.json for ng build

ng build command is used to compile your Angular application. When you need to compile your application for staging environment, you will need to use this command ng build --configuration staging. If you try to run this command now, you will get error message like this.

An unhandled exception occurred: Configuration ‘staging’ is not set in the workspace.

This is because you haven’t configured the staging configuration in angular.json. Go to angular.json in your root folder, copy production configuration in build configurations (see the snippet below for production configuration location) and paste the copied configuration right below the production configuration. Rename the pasted configuration to staging and the file replacement path to the staging environment file path. Now you can run ng build --configuration staging again and you should be able to build successful.

If you notice, there’s a defaultConfigurationat the end of configurations, this setting is to set the default configuration when you run ng build. If you didn’t specify any configuration, the builder will use the configuration configured at defaultConfiguration as the configuration. If you run ng build now, the default configuration will be production configuration.

{
[...]
"projects": {
"your-project-name": {
[...]
"architect": {
"build": {
[...]
"configurations": {
"production": { // 👈🏻👈🏻👈🏻 copy this section
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
fileReplacements: [
{
replace: 'src/environments/environment.ts',
with: 'src/environments/environment.production.ts',
},
],
"outputHashing": "all"
},
"staging": { // 👈🏻👈🏻👈🏻 paste here and rename it to staging
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
fileReplacements: [
{
replace: 'src/environments/environment.ts',
with: 'src/environments/environment.staging.ts', // change the environment file path to staging environment file path
},
],
"outputHashing": "all"
},
[...]
},
"defaultConfiguration": "production"
},
[...]
}
}
}
}

Extending angular.json for ng serve

ng serve is the command to use if you want to run your Angular application locally. This command will build your application, serve your application and rebuild on file changes. We have already set up ng build. ng serve will use the build configuration to build and serve your application. Then we need to add the serve configuration with the following format into the serve configurations.

"<environment name>": {
"browserTarget": "your-project-name:build:<environment name in build configuration>"
},

For our staging environment, the angular.json file will look like the following.

{
[...]
"projects": {
"your-project-name": {
[...]
"architect": {
[...]
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "your-project-name:build:production"
},
"staging": { // 👈🏻👈🏻👈🏻 add this serve configuration
"browserTarget": "your-project-name:build:staging"
},
"development": {
"browserTarget": "your-project-name:build:development"
}
},
"defaultConfiguration": "development"
},
[...]
}
}
}
}

Try to execute this command ng serve --configuration staging, you should be able to run your application with staging settings.

You might think, adding one environment into an Angular application has so many settings to configure and why can’t it be added automatically. Worry not, Angular CLI (version 15.1 onwards) will have a new schematic to add environment into your Angular application. It can be as simple as executing this command ng generate environments and a new environment will be added to your Angular application. You can read more about the discussion here: Bring back environment.ts to new projects · Issue #24381 · angular/angular-cli · GitHub

I find configuring a new environment into your Angular application is interesting. I always learnt something whenever I look into how Angular team implemented the framework. I hope you learn how to configure a new environment in your Angular application, even though there will be a schematic released for making your life a lot easier.

About environment.ts in your Angular applications (2024)
Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6268

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.