9
votes

I have several environment files for my Angular application :

  • environment.ts
  • environment.dev.ts
  • environment.prod.ts

I'd like to use default variables shared by all environments without duplicating them in every file. If I add a variable 'homeUrl' only in environment.ts for example :

export const environment = {
  production: false,
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
};

When I run the application with the dev configuration, my variables from environment.dev.ts are loaded properly but homeUrl is undefined as it's only declared in environment.ts file.

Is there a way to use default variables shared between environments without copying them ?

3

3 Answers

10
votes

You can import default variables from outside.

default.ts:

export const default = {
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
}

in environment.ts:

import {default} from 'default'

export const environment = {
  ...default,
  production: false
}

and import it in all files. So in this way you can modify only in default.ts file and will be apply automaticaly in all enviroments

1
votes

My answer will improve Oleg answer:

1. Base interface:

// config.ts
export interface Config {
   production: boolean;
   apiUrl: string;
   homeUrl: string;
   // added other need config definition.
}

2. Base environment:

// environment.base.ts
export const environmentBase = {
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
  // add more base, default, share config definitions.
}

3. Production environment:

// environment.prod.ts
export const environment: Config = {
    ...environmentBase,
  production: true,
}

4. Development environment:

// environment.dev.ts
export const environment: Config = {
    ...environmentBase,
  production: false,
}
0
votes

In addition to object spreading/assignment, you can just declare environment configs as a class that each inherit from your 'base' class.

// environment.ts
export class environment {
  static value = 'DefaultValue';
  static homeUrl = 'DefaultUrl';
} 

then in your other environment configs...

// environment.dev.ts, environment.prod.ts...
import { environment as EnvironmentBase } from './environment';

export class environment extends EnvironmentBase {
  static newThing = '??';
  static homeUrl = 'NewUrl'; // overridden
}

Things to note: these are now classes instead of object literals, so their properties should be static to match access. Also, you'd need to import the base config as a different name since you're defining a class with the same name in that file (or just make a separate base class altogether)/