Sonal Aggarwal
Sonal Aggarwal

Reputation: 373

How to deploy same angular build (dist) to multiple environments with different backend url?

Recently we came across this situation when we want to deploy same angular build (dist) using jenkins to multiple environments which implies different backend url.

Upvotes: 7

Views: 4430

Answers (2)

Debojyoti
Debojyoti

Reputation: 4841

Step - 1 : Create a js file

Just add a js file inside the assets directory

Let say the name is config.js and put all configurations inside that Eg :

var myAppGlobalConfig = { param1: 'value1' };
var BASE_URL = "http://xxx.backend.xxx/api/";
var GET_DATA = BASE_URL + "data.go";

Step - 2 : Include in index.html

Now in the index.html just include that script before any other script

<script src="assets/config.js"></script>

Step - 3: Use them inside your typescript classes

For example, you can assign http endpoint addresses.

this.http.get(window["DATA_URL"]).subscribe(...)

Further, in different environments just change global variables declared in the config.js

Upvotes: 1

Sonal Aggarwal
Sonal Aggarwal

Reputation: 373

This is how we solved it: (Reference: https://github.com/angular/angular-cli/issues/4318, Special thanks to: Michaël Arnauts)

  1. Create a js file in dist/assets folder and define a global js variable there:

    dist/assets/env.js

    window._env = {
        backendUrl: 'https://localhost:XXXX/',
    };
    
  2. Point to this global js variable in your environment.$ENV.ts file:

    src/environments/environment.$ENV.ts

    export const environment = {
        production: true,
        backendUrl: (<any>window)._env.backendUrl,
    };
    
  3. Add reference of js in your index.html

    ... <head> ... <script src="/assets/env.js"></script> </head> ...

  4. Create your environment value js files:

    src/environments/environment.$ENV.values.js

    window._env = {
        backendUrl: 'https://dev.example.com:XXXX/',
    };
    
  5. Create build (dist)

  6. Finally, at the time of deployment do:

    cp src/environments/environment.$ENV.values.js dist/assets/env.js

  7. Done!

Please note, step #1 is required so that you wouldn't require to do #6 on local.

Upvotes: 8

Related Questions