Check if JSON is available and import it if it is present

I have a configuration file that varies depending on the environment, so I added it to my `.gitignore` file.

In certain environments, the file may not exist at all. In such cases, default values will be used. Therefore, I am looking for a way to import a JSON file if it is present. The importing process can be done easily with this line of code:

import config from 'config.json';

If the file does not exist, an error message will display saying: "Error: Cannot find module 'config.json'."

My setup involves using Angular 8 and TypeScript.

Answer №1

Avoid excluding config.json from the .gitignore file as it is essential for compiling the source code. Instead, leverage Angular's "fileReplacements" functionality to set up distinct build environments.

For detailed instructions, visit https://angular.io/guide/build#configure-target-specific-file-replacements

You will need to create two specific files:

config.prod.json:

{ example: "Some data" }

config.json:

false

In your Angular configuration, specify that config.prod.json should be incorporated solely during production builds:

"configurations": {
"production": {
    "fileReplacements": [
        {
            "replace": "src/config.json",
            "with": "src/config.prod.ts"
        }
    ],

Now, you can import and utilize this file. During developer builds, it will result in a Boolean(false), whereas in production builds, it will be interpreted as a truthy value.

import config from 'config.json';

if(config) {
   console.log("Config for production");
} else {
   console.log("There is no config, then use something else");
}

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

Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng. [Currently, it is returning ...

Elevate your software from Angular 13 to 14 for Improved Routing Performance

Since updating to version 14, I've encountered the following error: An error occurred due to an invalid configuration of route 'map/operator/': a componentless route without children or loadChildren cannot have a named outlet set Below is ...

Explore the search bar with functional filtering for JSON items

I'm currently working on creating a dynamic filter bar integrated with a search functionality. My data is stored in JSON format, including details such as artist name, title, source, and more. Despite successfully retrieving results through console.lo ...

What causes the input field to lose focus in React after typing a character?

Currently utilizing React Mui for components and encountering no errors in either the Chrome inspector or terminal. How can this be resolved? No error notifications are being displayed by eslint or Chrome Inspector. The form submission functions correctl ...

What are the steps for utilizing functions with a variable parameter?

I have been working on a small project to practice my javascript skills, but I've run into an error that I can't seem to fix. I've tried researching a solution, but no luck so far. My goal is to create a program that generates silly insults ...

What is the quickest method for importing React.js Material Icons in a single line of code?

While working on my initial react.js project as a beginner, I encountered the frustration of having to import Material UI icons individually. This process made my code unnecessarily long and required me to repeatedly visit the browser to copy the icon li ...

Employing AJAX, PHP, and MYSQL in web development

Here is a simplified version of what I am trying to accomplish: This example illustrates the concept (using a select instead of multiple checkboxes): http://www.w3schools.com/php/php_ajax_database.asp The goal is to populate items based on the selected c ...

Issue with redirecting users back to the login page after accepting Keycloak required actions due to browser specific terms and conditions

My Keycloak version is 9.0 and my app's front end is built using Angular 8. I have enabled Terms and Conditions while setting the defaults to true. https://i.sstatic.net/URXM1.png I have customized the t&c page as desired, and it appears when u ...

Validation of forms, a standard button, crimson box, and sanitized data

How can I validate a popup form using jQuery and Javascript with a normal button instead of a submit button? The validation should mark empty fields with a red border box and display 'This field is empty' message. Additionally, the form data need ...

Tips for toggling helper messages during form validation using AngularJS

I've integrated ngMessages into my AngularJS application for form validation, and it has been quite helpful. However, I've encountered a challenge that I can't seem to figure out. For example, consider the following code snippet within my F ...

All You Need to Know About Jquery's Selector for Nested Elements

Could someone clarify if the Jquery Statement $(selecterA:not(selectorB), elementA) means "return those elements that match selectorA but not selectorB within elementA"? I am confused by a simple case in Fiddle#1, where both output statements using .length ...

Encoding PHP data into JSON format and using emojis

I received a JSON response that looks like this { "status": "\ud83d\ude0e" } Can anyone advise me on how to convert it to 1f60e using PHP? ...

What steps can be taken to troubleshoot an AJAX error that does not display any error messages?

Within my ajax code, I have the following: $(document).ready(function(){ $("form input#dodaj").click(function(){ var s = $("form input#zad").val(); var str = "<li>"+s+"</li>"; $.ajax( { type: "GET", ...

Sorting the output with gulp and main-bower-files (gulp-order is not functioning)

Hello, I'm a Java engineer diving into the world of Javascript for the first time. Apologies in advance if my information is lacking or incorrect! I am currently working on a gulp build script and utilizing bower to manage dependencies for my JS fron ...

Steps to enable navigation to external pages from a ReactJS app

I am working on a simple ReactJS application: [Demo] [Source] I am trying to implement navigation within the app from external sources without refreshing the web page. This functionality should be similar to using this.props.history.push(...). /public/i ...

403 Forbidden Error encountered when attempting to incorporate JavaScript

I have encountered an issue with my code where I am trying to grab a form from another website. The PHP code in the header is meant to sanitize the GET string in the URL for security purposes. Essentially, I have a page called order.html which functions pr ...

What is the best way to link a JavaScript file from a node package in an HTML document?

After developing a Node.js Express App using JetBrains WebStorm, I utilized npm (via File->Settings->Node.js and NPM) to install a package called validator, specifically designed for string validation. The installation of the package went smoothly u ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

Issue: The spy MovieService.getWatchListedMovies was expected to have been called during the angular Unit Testing, but it was

There is a component file named watchlist which relies on MovieService(service) to retrieve movies. Invoking ngOnInit() will trigger MovieService.getWatchlistedMovies() The component code is provided below, export class WatchlistComponent implements ...

Mastering the nesting of keys in Typescript.Unlock the secrets of

I encountered a situation where the following code snippet was causing an issue: class Transform<T> { constructor(private value: T) {} } class Test<T extends object> { constructor(private a: T) {} transform(): { [K in keyof T]: Transfo ...