Programming

How to set environment via ng serve in Angular 6

19 September 2026 · 9 min read

How to set environment via ng serve in Angular 6

Angular 6 brought significant improvements to the developer experience, including streamlined ways to manage different environments. One crucial aspect of Angular development is configuring your application to behave differently based on the environment it’s running in (e.g., development, testing, production). The ng serve command, the workhorse for local development, provides several mechanisms to set environment via ng serve in Angular 6. This allows you to quickly switch between configurations without altering your core application code. Understanding these methods is essential for efficient Angular development, enabling you to use different API endpoints, feature flags, or even mock data depending on the selected environment. This article will guide you through the various approaches to configure environments when using ng serve, ensuring a smooth and productive development workflow.

Understanding Angular Environments

Before diving into the specifics of using ng serve for environment configuration, it’s important to understand how Angular manages environments in general. Angular projects typically include an environments folder in the src directory. This folder contains environment-specific configuration files, such as environment.ts (for development) and environment.prod.ts (for production). These files usually define a JavaScript object with key-value pairs representing environment-specific settings like API URLs, authentication parameters, or debug flags. These environment files are crucial for adapting your application to different scenarios, ensuring that development builds use local APIs while production builds connect to live data. This separation of concerns makes your application more maintainable and less prone to errors.

The Angular CLI leverages these environment files during the build process. When you build your application for production (e.g., using ng build –prod), the CLI automatically replaces the default environment.ts file with the environment.prod.ts file. This substitution ensures that the production build uses the correct configuration. Similarly, you can create custom environment files for staging, testing, or any other environment your application requires. Properly managing these environment files is a cornerstone of Angular development best practices, preventing accidental exposure of sensitive information in production and simplifying debugging in development.

Key benefits of using environment files include:

  • Improved code maintainability and organization.
  • Reduced risk of deploying incorrect configurations to production.
  • Simplified switching between different environment settings.

Configuring Environments with ng serve

While the ng build command directly utilizes the environment files based on the –prod flag, ng serve requires a slightly different approach to utilize environment-specific configurations. There are a couple of primary methods to set environment via ng serve in Angular 6. One is by defining a custom configuration in your angular.json file and using the –configuration flag with ng serve. The other involves setting an environment variable. Let’s explore these methods in detail.

The –configuration flag allows you to specify a custom build configuration defined in your angular.json file. Within this configuration, you can override specific properties, including the environment file used. For instance, you might define a “staging” configuration that points to environment.staging.ts. This approach provides a clean and structured way to manage different environments during development. Another powerful feature is the ability to define different optimization levels or even different compilers depending on the specified configuration. This flexibility makes it easy to simulate production-like conditions during local development.

Alternatively, you can leverage environment variables. By setting an environment variable (e.g., NODE_ENV=staging), you can instruct your application to load the corresponding environment file. This approach typically involves modifying your build scripts or using a library like dotenv to load environment variables from a .env file. While slightly more complex to set up initially, this method offers greater flexibility and is well-suited for CI/CD pipelines where environment variables are commonly used to configure deployments. According to a Stack Overflow survey, approximately 60% of developers use environment variables to manage configuration settings, highlighting its widespread adoption. Source: Stack Overflow Blog

Step-by-Step Guide: Using the –configuration Flag

This section provides a step-by-step guide on how to set environment via ng serve using the –configuration flag. This is often the simplest approach for basic environment switching during development, and is easily understandable for developers of any experience level.

  1. Create a new environment file: Start by creating a new environment file, such as environment.staging.ts, in your src/environments directory.
  2. Define your configuration in angular.json: Open your angular.json file and locate the “architect” section, then the “serve” and “configurations” sections. Add a new configuration for your staging environment. For example:
    "staging": { "browserTarget": "your-app-name:build:staging" } 
    
  3. Define the build configuration for staging: In the “architect” section, locate “build” and “configurations”. Add your staging build configuration:
    "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ], "optimization": false, "outputHashing": "all", "sourceMap": true, "extractCss": false, "namedChunks": false, "aot": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": false } 
    
  4. Serve your application: Run the command ng serve –configuration=staging to serve your application using the staging configuration.

By following these steps, you can easily switch between different environments using the –configuration flag. This approach is particularly useful for testing changes in a staging environment before deploying them to production. Remember to adjust the configuration names and file paths to match your specific project structure.

Leveraging Environment Variables

Using environment variables offers a more flexible approach to set environment via ng serve, especially in complex development workflows and CI/CD pipelines. This method involves setting an environment variable that your application can then read to determine the correct environment configuration to load. It often relies on using libraries to read the variables. This approach may require a bit more setup initially, but it provides significant advantages in terms of flexibility and portability.

First, you’ll need to install a library like dotenv (npm install dotenv). Then, create a .env file in the root of your project and define your environment variables there (e.g., API_URL=https://staging.example.com). Next, in your main.ts or a similar entry point, load the environment variables using dotenv. Finally, modify your environment files to dynamically load the configuration based on the environment variable. This allows you to switch environments simply by changing the value of the environment variable, without modifying your Angular code directly. You can then access those variables using process.env.API_URL.

Here are some benefits of using environment variables:

  • Environment variables are easily configurable in CI/CD pipelines.
  • Sensitive information (e.g., API keys) can be stored securely as environment variables.
  • Environment variables provide a consistent way to manage configurations across different environments.
Infographic here
FAQ: Common Questions About Angular Environments ------------------------------------------------
How do I access environment variables in my Angular components?
You can access environment variables by importing the environment object from your environment file (e.g., import { environment } from '../environments/environment';). Then, you can access the variables using dot notation (e.g., environment.apiUrl).
Can I use different environment files for different build targets?
Yes, you can define different build targets in your angular.json file and specify the corresponding environment file for each target. This allows you to have separate configurations for development, staging, and production.
What is the best practice for storing sensitive information in environment files?
For sensitive information, it's best to use environment variables instead of storing them directly in your environment files. Environment variables can be securely managed by your operating system or CI/CD pipeline. Using a tool like [HashiCorp Vault](https://www.vaultproject.io/) is a good option for larger projects. Never commit sensitive information to your source code repository.
How to set environment via ng serve with a custom file?
You can't directly specify a custom environment file with ng serve without modifying your angular.json configuration. The --configuration flag is the recommended way to achieve this.
Setting up environments correctly is critical for any non-trivial Angular application. The ability to easily switch between configurations using ng serve speeds up development and reduces the risk of errors. Remember to choose the method that best suits your project's needs and complexity. For simple projects, the --configuration flag might suffice. For more complex projects, environment variables may offer greater flexibility.

By thoughtfully implementing environment configurations, you create a more robust, maintainable, and adaptable Angular application. Don’t underestimate the power of well-defined environments; they are an essential part of a professional development workflow. Further enhance your Angular skills by exploring topics like lazy loading modules or optimizing build performance. You can also find more information on the official Angular documentation. Angular Environment Files Guide. Consider exploring advanced techniques like using custom webpack configurations for even finer-grained control over your build process. And remember, consistent environment management contributes significantly to a smoother development and deployment experience, so take the time to set it up right!

Ready to take your Angular development to the next level? Explore our other resources and tutorials to learn more about advanced Angular techniques. Check out our article on optimizing Angular performance for tips on building faster and more efficient applications.

Question & Answer :
I am trying to update my Angular 5.2 app to Angular 6. I successfully followed instructions in the Angular update guide (including the update of angular-cli to v6), and now I am trying to serve the app via

ng serve --env=local 

But this gives me error:

Unknown option: ‘–env’

I use multiple environments (dev/local/prod), and this is the way it was working in Angular 5.2. How can I set the environment now in Angular 6?

You need to use the new configuration option (this works for ng build and ng serve as well)

ng serve --configuration=local 

or

ng serve -c local 

If you look at your angular.json file, you’ll see that you have finer control over settings for each configuration (aot, optimizer, environment files,…)

"configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] } } 

You can get more info here for managing environment specific configurations.

As pointed in the other response below, if you need to add a new ’environment’, you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.

Adding a new environment

Edit: To make it clear, file replacements must be specified in the build section. So if you want to use ng serve with a specific environment file (say dev2), you first need to modify the build section to add a new dev2 configuration

"build": { "configurations": { "dev2": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.dev2.ts" } /* You can add all other options here, such as aot, optimization, ... */ ], "serviceWorker": true }, 

Then modify your serve section to add a new configuration as well, pointing to the dev2 build configuration you just declared

"serve": "configurations": { "dev2": { "browserTarget": "projectName:build:dev2" } 

Then you can use ng serve -c dev2, which will use the dev2 config file

You may need to delete .angular to make the new environment visible.