I have several environment files for my Angular application :
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 ?
Introduction. If you're building an app that uses an API, you'll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.
A project's src/environments/ folder contains the base configuration file, environment. ts , which provides a default environment. You can add override defaults for additional environments, such as production and staging, in target-specific configuration files. For example: myProject/src/environments.
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
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,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With