Custom Environments in the Angular CLI

Austin
2 min readJan 25, 2018

--

Custom environment variables are something that we all use to conditionally set options in our application. Angular comes with a dev and prod environment configured by default. But what if we want to extend this to have something like a mock environment where we can use mock data rather than the real backend? The team behind the Angular CLI has this handled for you…

To get started, lets look under the environments folder and create a new file called environment.mock.ts and make it look something like this:

export const environment = {
production: false,
envName: 'mock'
};

We also need to add envName to our other environment files too. So in environment.ts add envName: 'dev' and environment.prod.ts add envName: 'prod'.

In our .angular-cli.json we need add our new environment to the environments object in our app. That looks like:

"environments": {
"dev": "environments/environment.ts",
"mock": "environments/environment.mock.ts",
"prod": "environments/environment.prod.ts"
}

Now in our code, we can do our logic checking for our new environment variables mock like:

import { environment } from './environments/environment';@NgModule({
imports: [
CommonModule,
environment.envName === 'mock' ?
HttpClientInMemoryWebApiModule.forRoot(InMemoryDb) :
[]
]
})
export class ServicesModule {}

You can also make your tests use this new environment variable by editing karma.config.js and setting angularCli: { environment: 'mock' } .

Next, we start our app passing the environment name like: ng s -e mock and presto our environment is set to mock and using our mock backend!

I’m #ngPanda

I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc!

--

--

Austin

Crafter of Software • Lover of #JavaScript #goldendoodles & #opensource