What is environment.ts?
environment.tsexport const environment = {
production: false,
apiUrl: 'http://localhost:3000/api',
};
environment.prod.tsexport const environment = {
production: true,
apiUrl: 'https://api.example.com',
};
How Does Angular Use These Files?
angular.json"configurations": {
"production": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}]
}
}
bashng build --configuration production
How to Use environment in Your App
import { environment } from '../environments/environment';
...
console.log(environment.apiUrl);
Adding Custom Environments (Staging, QA, etc.)
environment.staging.tsexport const environment = {
production: false,
apiUrl: 'https://staging-api.example.com',
featureFlag: true,
};
angular.json"configurations": {
"staging": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}]
}
}
bashng build --configuration staging
Alternatives: Runtime Configuration
In some projects, you may want to inject values at runtime (e.g., from a config.json hosted on your server). This decouples environment config from your build and can be changed without re-deploying.
A common strategy is to load a JSON config before bootstrap:
main.tsfetch('/assets/config.json')
.then((response) => response.json())
.then((config) => {
platformBrowserDynamic([
{ provide: APP_CONFIG, useValue: config }
]).bootstrapModule(AppModule);
});
Conclusion
The environment.ts system in Angular is a powerful way to manage per-environment configuration. It’s simple, efficient, and tightly integrated with the Angular CLI. As your app grows, adopting good practices around environments ensures better separation of concerns, easier deployments, and fewer bugs.