Day 27 Challenge: Switch Environment in a Local Angular Project

sunny gsunny g
5 min read

Challenge Overview:

In this challenge, you will learn how to switch between different environments (such as development, production, staging) in an Angular application. Angular provides a way to manage different environments through environment-specific configuration files, and you'll set up the ability to easily switch between them in your local development setup.

By the end of the challenge, you'll be able to:

  1. Create multiple environment files for different settings.

  2. Switch environments based on the build configuration.

  3. Use Angular CLI to test your app in various environments.

  4. Understand the power of using environment files to manage different configurations for production and development.


Objective:

  1. Create environment files for development, production, and staging.

  2. Configure Angular's angular.json to set up multiple environments.

  3. Switch between environments using Angular CLI commands.

  4. Use the environment variables in your app (e.g., API URLs, feature flags, etc.).


Step 1: Create Environment Files

Angular comes with a default environment configuration in the src/environments folder, typically having two environments: environment.ts (development) and environment.prod.ts (production).

  1. Go to src/environments/ and find these default files:

  2. Create Additional Environment Files:

    For this challenge, let’s add a staging environment to simulate multiple environments.

    • Create a new file called environment.staging.ts in the src/environments/ folder:

        // src/environments/environment.staging.ts
        export const environment = {
          production: false,
          apiUrl: 'https://staging-api.example.com',
          featureFlag: true,
        };
      
    • Modify environment.ts (development):

        // src/environments/environment.ts
        export const environment = {
          production: false,
          apiUrl: 'https://dev-api.example.com',
          featureFlag: true,
        };
      
    • Modify environment.prod.ts (production):

        // src/environments/environment.prod.ts
        export const environment = {
          production: true,
          apiUrl: 'https://api.example.com',
          featureFlag: false,
        };
      

Step 2: Configure angular.json for Multiple Environments

In Angular, the environment file is replaced based on the build configuration. You need to update the angular.json to add your new staging environment.

  1. Open angular.json:

    Look for the fileReplacements section in the build and configurations section of your app. This is where Angular switches between the environment.ts and other environment files based on the build mode.

  2. Add staging Configuration:

    Find the build configurations for the production and development modes. Now add the staging mode. Under the projects -> [your-app] -> architect -> build -> configurations, you’ll see:

     "configurations": {
       "production": {
         "fileReplacements": [
           {
             "replace": "src/environments/environment.ts",
             "with": "src/environments/environment.prod.ts"
           }
         ]
       },
       "development": {},
       "staging": {
         "fileReplacements": [
           {
             "replace": "src/environments/environment.ts",
             "with": "src/environments/environment.staging.ts"
           }
         ]
       }
     }
    
    • staging Configuration: This ensures that when building or serving the app with the staging configuration, the environment.staging.ts file is used in place of environment.ts.

Step 3: Modify Code to Use Environment Variables

Now, let’s use the environment variables in your app.

  1. Open app.component.ts and use the environment variable:

     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 {
       title = 'Switch Environment Demo';
       apiUrl = environment.apiUrl;
       featureFlag = environment.featureFlag;
     }
    
  2. Display the environment variables in the template (app.component.html):

     <div>
       <h1>{{ title }}</h1>
       <p>API URL: {{ apiUrl }}</p>
       <p>Feature Flag Enabled: {{ featureFlag }}</p>
     </div>
    

    Now, depending on the environment (development, staging, or production), this component will display the correct apiUrl and featureFlag.


Step 4: Switch Between Environments Using Angular CLI

You can switch between environments when building or serving your application using the Angular CLI.

  1. For Development:

    By default, when you run ng serve or ng build, Angular will use environment.ts (development).

     ng serve
    

    This will use the development environment and show the dev-api.example.com as the API URL.

  2. For Production:

    To build the app for production, use the --prod flag, which automatically replaces environment.ts with environment.prod.ts.

     ng build --prod
    

    This will use the production environment and show the api.example.com as the API URL.

  3. For Staging:

    To use the staging environment, run the build command with the --configuration flag set to staging:

     ng build --configuration=staging
    

    This will replace environment.ts with environment.staging.ts and show the staging-api.example.com as the API URL.

    Similarly, you can serve the app in staging mode:

     ng serve --configuration=staging
    

Step 5: Verify the Environment Switch

  1. Run the app in development mode:

     ng serve
    

    Open http://localhost:4200 and check if the displayed API URL is https://dev-api.example.com.

  2. Run the app in production mode:

     ng serve --prod
    

    Check if the displayed API URL is https://api.example.com.

  3. Run the app in staging mode:

     ng serve --configuration=staging
    

    Verify that the displayed API URL is https://staging-api.example.com.


Bonus Challenge: Use Environment Variables in Different Parts of Your Application

  1. Use the environment variables in services, for example, to dynamically switch API endpoints in your HTTP requests.

  2. Create a feature that changes behavior based on the featureFlag from the environment file. For example, hide or display certain components depending on the feature flag.


Conclusion

By completing this challenge, you will learn how to:

  • Create and manage multiple environment files in an Angular project.

  • Switch between environments (development, production, staging) using Angular CLI.

  • Use environment-specific configurations in your Angular components and services.

Requirements to Submit:

  1. An Angular project with at least three environments: development, production, and staging.

  2. The application correctly switches between environments based on the build configuration.

  3. Proper use of environment variables to display or configure API URLs, feature flags, and other settings.

Good luck, and happy coding! 🎉

0
Subscribe to my newsletter

Read articles from sunny g directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sunny g
sunny g