How do I implement environment-specific configuration settings in AngularJS and Typescript

871 views Asked by At

I'm putting together a AngularJS+Typescript+VisualStudio project. I want to have a configuration file with constants in it that control different settings (e.g., REST API URLs and environment names). How is this typically done in this kind of project?

I might have a dev config file called app.dev.config.ts like this:

module app.config {
    export class ConfigSettings {
        static environment(): string { return "dev"; }
        static dataApiBaseUrl(): string { return "DevDataService"; }
    }
}

and an app.prod.config.ts like this:

module app.config {
    export class ConfigSettings {
        static environment(): string { return "prd"; }
        static dataApiBaseUrl(): string { return "PrdDataService"; }
    }
}

Of course this doesn't actually work because these two classes have the same name.

I need to set this up in a way so that I build this only once in my build server, and then can deploy this to a fixed (3) number of environments. Maybe this means that when I go to deploy this to some environment, I have an additional step where I rename a config file. This is what I do for C# projects and their config files.

I've searched around online for this, but all I can find is references to tsconfig.json files.

1

There are 1 answers

0
user2023861 On BEST ANSWER

I found a solution for this.

1) I put together separate config files like env.dev.ts and env.prd.ts in my project. Their contents look like this:

angular.module('compdb') //module name matches my main module
    .constant('env', 'prd')
    .constant('key1', 'prd value 1')
    .constant('key2', 'prd value 2');

2) Visual Studio transpiles these to env.dev.js, etc.

3) In my gulp file, I copy the env.*.js files to my output directory.

4) In my Index.cshtml file, I include env.js. I include this after my scripts that create the compdb angular module

5) When I deploy my code to any environment, I rename the appropriate config file (e.g., env.prd.js) to env.js