w3resource

Building and serving Angular apps

Configuring application environments

You can define different named build configurations for your project, such as stage and production, with different defaults.

Each named build configuration can have defaults for any of the options that apply to the various build targets, such as build, serve, and test. The Angular CLI build, serve, and test commands can then replace files with appropriate versions for your intended target environment.

The following figure shows how a project has multiple build targets, which can be executed using the named configurations that you define.


Angular Bypass Security Component

Configure environment-specific defaults

A project's src/environments/ folder contains the base configuration file, environment.ts, which provides a default environment. You can add override defaults for additional environments, such as production and staging, in target-specific configuration files.

For example:

+--myProject/src/environments/
                   +--environment.ts
                   +--environment.prod.ts
                   +--environment.stage.ts

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen file structure by w3resource (@w3resource) on CodePen.


The base file environment.ts, contains the default environment settings. For example:

export const environment = {
  production: false
};

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen GayjeY by w3resource (@w3resource) on CodePen.


The build command uses this as the build target when no environment is specified. You can add further variables, either as additional properties on the environment object, or as separate objects. For example, the following adds a default for a variable to the default environment:

export const environment = {
  production: false,
  apiUrl: 'http://my-api-url'
};

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen xNpRxX by w3resource (@w3resource) on CodePen.


You can add target-specific configuration files, such as environment.prod.ts. The following sets content sets default values for the production build target:

export const environment = {
  production: true,
  apiUrl: 'http://my-prod-url'
};

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen dEJOPe by w3resource (@w3resource) on CodePen.


Using environment-specific variables in your app

The following application structure configures build targets for production and staging environments:

+-- src
    +-- app
        +-- app.component.html
        +-- app.component.ts
    +-- environments
        +-- environment.prod.ts
        +-- environment.staging.ts
        +-- environment.ts

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen XwVNmR by w3resource (@w3resource) on CodePen.


To use the environment configurations you have defined, your components must import the original environments file:

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

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen JqMbGM by w3resource (@w3resource) on CodePen.


This ensures that the build and serve commands can find the configurations for specific build targets.

The following code in the component file (app.component.ts) uses an environment variable defined in the configuration files.

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() {
    console.log(environment.production); // Logs false for default environment
  }
  title = 'app works!';
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen dEJOMK by w3resource (@w3resource) on CodePen.


Configure target-specific file replacements

The main CLI configuration file, angular.json, contains a fileReplacements section in the configuration for each build target, which allows you to replace any file with a target-specific version of that file. This is useful for including target-specific code or variables in a build that targets a specific environment, such as production or staging.

By default, no files are replaced. You can add file replacements for specific build targets. For example:

"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ],
    ...

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen JqMbRp by w3resource (@w3resource) on CodePen.


This means that when you build your production configuration (using ng build --prod or ng build --configuration=production), the src/environments/environment.ts file is replaced with the target-specific version of the file, src/environments/environment.prod.ts.

You can add additional configurations as required. To add a staging environment, create a copy of src/environments/environment.ts called src/environments/environment.staging.ts, then add a staging configuration to angular.json:

"configurations": {
  "production": { ... },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen GayNrL by w3resource (@w3resource) on CodePen.


You can add more configuration options to this target environment as well. Any option that your build supports can be overridden in a build target configuration.

To build using the staging configuration, run the following command:

```ng-build --configuration=staging```

You can also configure the serve command to use the targeted build configuration if you add it to the "serve:configurations" section of angular.json:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "your-project-name:build"
  },
  "configurations": {
    "production": {
      "browserTarget": "your-project-name:build:production"
    },
    "staging": {
      "browserTarget": "your-project-name:build:staging"
    }
  }
},

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen arEByq by w3resource (@w3resource) on CodePen.


Configure size budgets

As applications grow in functionality, they also grow in size. The CLI allows you to set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define.

Define your size boundaries in the CLI configuration file, angular.json, in a budgets section for each configured environment

{
  ...
  "configurations": {
    "production": {
      ...
      budgets: []
    }
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen WBdoXr by w3resource (@w3resource) on CodePen.


You can specify size budgets for the entire app, and for particular parts. Each budget entry configures a budget of a given type. Specify size values in the following formats:

  • 123 or 123b: Size in bytes
  • 123kb: Size in kilobytes
  • 123mb: Size in megabytes
  • 12%: Percentage of size relative to baseline. (Not valid for baseline values.)

When you configure a budget, the build system warns or reports an error when a given part of the app reaches or exceeds a boundary size that you set.

Each budget entry is a JSON object with the following properties:

Property Value
type The type of budget. One of: bundle - The size of a specific bundle. initial - The initial size of the app. allScript - The size of all scripts. all - the size of the entire app. anyScript - The size of any one script.any - The size of any file.
name The name of the bundle (for `type=bundle`).
baseline The baseline size for comparison.
maximumWarning The maximum threshold for warning relative to the baseline.
maximumError The maximum threshold for error relative to the baseline.
minimumWarning The minimum threshold for warning relative to the baseline.
minimumError The minimum threshold for error relative to the baseline.
warning The threshold for warning relative to the baseline (min & max).
error The threshold for error relative to the baseline (min & max).

Previous: Browser support
Next: Simple deployment options



Share this Tutorial / Exercise on : Facebook and Twitter