Angular Create Multiple Environment Files

Advertisement

Advertisement

Introduction

With Angular 7, when you create an app with the default app generator, it creates two basic environment files: development and production.

When you run ng serve it serves with the development environment settings. To build production you run ng build --prod.

My problem was that I wanted more environments, particularly, a local, development, and production environment. So I wanted to add a new settings file for local work and have ng serve use the local settings.

This will look at how to create additional environment settings files, how to use ng build with your custom environment, and how to use ng serve with the custom environments too.

The serve command first calls build, so we will first look at how to update the build step and then the serve action.

Update angular.json build configurations

To tell Angular to use a different environment file, the build configuration must be updated.

In the angular.json file there is a section named build which has a section named configurations inside of it. This is where you can override settings for the build process. By default there is only one entry in configurations named production which sets some production values and replaces environment.ts with environment.prod.ts. We will need to do something similar.

For example, update the build section in angular.json to look like this:

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

At this point you can build the application with the settings like this:

ng build --configuration local
# or
ng build -c local

Update angular.json serve configurations

Now that the build process is in place, you can update the serve configurations.

In the angular.json file, there is a section named serve that has its own configurations section. By adding a new configuration here, you can use the ng serve command to launch your site with the custom configuration.

  // ...
  "serve": {
    // ..
    "configurations": {
      "production": {
        "browserTarget": "MyProject:build:production"
      },
      "local": {
        "browserTarget": "MyProject:build:local"
      }
    }
  },
  // ...

By adding this serve configuration and telling it to use our custom build configuration, we can serve our application like this:

ng serve --configuration local
# or
ng serve -c local

Conclusion

After reading this, you should know how to add custom build and serve configurations to your Angular app and how to run them.

Advertisement

Advertisement