Is it possible to generate assets or files in Angular 4 based on different environments?

Is it possible to generate assets/files on build in our Angular app using environment variables?

We are looking to create an 'auth/settings.js' file in the assets folder with client id's and apiUrl's unique to each environment. These values will be used in the index.html outside of the angular app bootstrap.

For example, we would like to export the values in the environment.ts file into a js/json file outputted to the assets folder for use in index.html

export const environment = {
production: false,
title: 'default',
clientId: 'xxxx-xxxx-xxxx-xxxx-xxxx',
clientUrl: 'https://localhost:4200/app',
apiUrl: 'https://localhost/api'
};

I have come across the concept of multiapps which might help:

https://github.com/angular/angular-cli/wiki/stories-multiple-apps

However, the process seems quite manual and repetitive, as we will have multiple versions of the build. Is there a way to declare common settings once and extend them for extra app settings (inheritance)?

Thank you

Answer №1

In our scenario, we have a setup where we utilize both a config.json file and config.[env-name].json files within the app/config directory that is specified in the project assets. Prior to Angular bootstrap, the config.json file is fetched using the browser's Fetch API.

On our build server, we replace the content of the config.json with either config.staging.json or config.prod.json based on the environment being built. Additionally, we generate an AppSettings class during bootstrap. Here is an example:

fetch(configUrl, { method: 'get' })
.then((response) => {
  response.json()
    .then((data: any) => {
      if (environment.production) {
        enableProdMode();
      }
      platformBrowserDynamic([{ provide: AppSettings, useValue: new AppSettings(data.config) }]).bootstrapModule(AppModule);
    });
});

UPDATE: If you need to include specific values in your index.html based on the environment, consider making these changes on the build server. You can perform a string replace operation on the values or have separate index.[env-name].html files to overwrite the main index.html during different environment builds.

For further information, refer to the following issues:
- https://github.com/angular/angular-cli/issues/7506
- https://github.com/angular/angular-cli/issues/3855

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showcasing an image on an HTML page

I am encountering an issue with my HTML page that includes a Button. When clicked, it is supposed to display an image using an Ajax call. The functionality works properly in Postman Rest Client. However, when accessed through a browser, it only shows raw ...

Fetching data from local JSON file is being initiated twice

I need some help understanding why my code is downloading two copies of a locally generated JSON file. Here is the code snippet in question: function downloadJson(data, name) { let dataStr = 'data:text/json;charset=utf-8,' + encodeURICompo ...

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

Tips on how to confirm that the content of the angular form begins and concludes with a specific string

For user input that must start with a specific string, such as XYZ, have business data in between, and end with ENDXYZ within a textview, I am utilizing the Angular framework for the UI. <div class="mb-3 col-md-5"> <label for=&qu ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Problem with JQuery binding

Currently, I have set up my radio buttons with jQuery bind using the code below: jQuery().ready(function() { jQuery("input[name='rank_number']:radio").bind('change', function(){ submitSelectedRank(); }); }); While th ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Instructions on how to toggle the visibility of a div when hovering over a different a tag

To keep things simple, I'm looking to create a visibility toggle effect on a div when someone hovers over an anchor tag. Similar to the behavior of the four buttons on this example link: The issue I'm facing is that I want the div to appear or b ...

Tips for declaring and utilizing multiple functions within an Angular JS Factory, as well as executing one function inside another

Could someone assist me in creating multiple functions within an AngularJS Factory? I am looking to access the returned value from one function and process it in another function. I attempted the code below without success. In the following function, I wa ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

The precision of the stopwatch is questionable

Just starting out with JS and jquery, I quickly put together a stopwatch code in JS that seems to work accurately up to 10 minutes. The issue arises after the 10-minute mark where it starts falling a few seconds behind (I compared it to a digital stopwatc ...

Typescript is being lenient with incorrect use of generics, contrary to my expectations of error being thrown

Encountered a puzzling Typescript behavior that has left me confused. Take a look at the following code snippet: interface ComponentProps<T> { oldObject: T } function Component<T>({ oldObject }: ComponentProps<T>) { const newObject = ...

Top method for utilizing overlays

Is there a method to randomly select hex codes for specific colors? I want to replicate the design in this image through coding. Image Here is the code I have so far: HTML <div id="group"> <div class="sub red panel"> </div><!--su ...

JavaScript: experiencing difficulty incorporating API string into JSON format

When I am trying to add values to a JSON object manually, it works fine: Code: for (var k = 0; k < result.length; k++) { result[k]["sender"] = k; } https://i.sstatic.net/jnbpw.png However, when I fetch values from an API and att ...

Having trouble transferring captured images to Firebase storage

I am currently working on creating a small Ionic 2 application that is capable of capturing images using the camera and then uploading those images to Firebase storage. Additionally, I aim to store the URLs of the captured images in the Firebase database. ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

What is the best way to retrieve an object in Angular 5?

I am encountering an issue with retrieving an Array in Angular. The problem is that I have to click the button twice to retrieve the Array data. I would like it to work with just one click (refer to the image at the end of the page). @Injectable() export ...

Tips on ensuring the callback function is properly called when it is passed as an argument to another function

I am facing a challenge with my typescript method that needs to call another method, on(), which requires a callback method. I want the myConnect() method to wait until the callback is executed. I believe this involves using a promise, but I'm struggl ...