Vortilion
Vortilion

Reputation: 424

Global constant in Angular depending on build configuration

I am currently trying to migrate an AngularJS 1.6 application, completely build in components, to Angular 12. So far everything works, but I am having one big problem cause of our project structure:

The project is a multi-client portal with several different "profiles" for each client (different assets, API-Urls etc.), Backend is Java, Frontend AngularJS/Angular Hybrid (now). Depending on the frontend build configuation via Angular-CLI I build the frontend for the corresponding client.

My problem now is: In the AngularJS-Application we were adding AngularJS-constants to the AngularJS-App

(function () {
'use strict';

function constant() {
    return {
        CUSTOMER_NAME : 'client name',
        // and many more...
    };
}

angular
    .module('our.module')
    .constant('CLIENT_CONSTANTS', constant());
})();

depending on the build-configuration (all scripts have been added to the index.html cause we werent using webpack before), e.g.

<script src="${clientName}"></script>

Where ${clientName} was the placeholder for the client, which was replaced by gulp during build. This isnt possible anymore with Angular, as Angular does the injection of the script-Tags via Angular-CLI. It seems that it isn't possible to pass variables from the Angular-CLI to the code, which would exactly be what I need :-( So I am wondering how I can add global constants depending on the Angular-CLI-Build configuration! Any ideas? I tried adding the constants-file to the configurations' script-Block, to no avail. (

I refactored the clients-file to TypeScript:

export const PROFILE_CONSTANTS = {
    CUSTOMER_NAME : 'client name',
    // and many more
}

I also tried to dynamically import the file via ES6-import, which also isn't possible. I'm running out of ideas now.

Upvotes: 0

Views: 754

Answers (1)

danday74
danday74

Reputation: 57036

You probably want to use Angular configurations (previously known as Angular environments).

Heres an example setup to get you started:

https://dev.to/mikgross/set-up-multiple-environments-in-angular-376c

Note that this has changed a fair bit over the course of time so make sure you are applying a solution that relates to Angular 12.

The only thing the above article misses out is how to access the variables for a given configuration. Basically you import from environment/environment.ts and the Angular server or build will serve up the correct environment file based on the fileReplacements you specify in angular.json

Note that in the example given, they are creating different configurations for different servers, but you can equally apply this to creating different configurations for different clients.

Upvotes: 1

Related Questions