Environments
What is an environment?
An environment is a set of variables that define the behavior of an application. For example, you can have a development environment, a staging environment, and a production environment. Each environment will have different variables, such as the API URL, the API key, and the API secret.
How do I create an environment?
To create the environments folder you can run:
ng generate environments
This will create a folder called environments in the src folder. Inside the environments folder, you will find two files: environment.ts and environment.prod.ts. The environment.ts file will contain the variables for the development environment, and the environment.prod.ts file will contain the variables for the production environment.
How do I use an environment?
To use an environment, you can import it in your component or service, and then use it like this:
import { environment } from '../environments/environment';
export class AppComponent {
title = environment.title;
}
How do I use different environments?
The main CLI config file, angular.json
contains a fileReplacements section in the configuration for each build target. We will use that to specify which environment file to use for each build target. For example, to use the production environment for the production build target, you can add the following to the production configuration:
{
"configurations": {
"development": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
},
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
}
}
To use different environments, you can use the --configuration flag when running the ng serve or ng build commands. For example, to use the production environment, you can run:
ng serve --configuration=production
To run the development environment, you can run:
ng serve --configuration=development
ng serve
is a command that starts a development server. It is used to run the application locally and should not be used for production. If you want to build the application for production, you should use ng build
instead. ng build
supports the same flags as ng serve
, so you can use the --configuration
flag to specify which environment to use.
The fields in the environment files are not merged with the fields in the environment.ts
file, this is due to the fact that the file is replaced, not merged.