An issue has arisen with the Angular environment.ts file related to a JSON problem. On

I've been encountering an issue with importing JSON files into TypeScript. I've set up my tsconfig.json file following the standard conventions, but it's still not working in the environment.ts file. Interestingly enough, it works perfectly fine in the environment.prod.ts file.

environment.ts

import { domain, clientId, audience, serverUrl } from '../../auth_config.json';

export const environment = {
  production: false,
  auth: {
    domain,
    clientId,
    redirectUri: window.location.origin,
    audience,
  },
  dev: {
    serverUrl,
  },
};

ERROR --> Cannot find module '../../auth_config.json'. Consider using '--resolveJsonModule' to import a module with a '.json' extensionts(2732)

environment.prod.ts

import { domain, clientId, audience, serverUrl } from '../../auth_config.json';

export const environment = {
  production: true,
  auth: {
    domain,
    clientId,
    redirectUri: window.location.origin,
    audience,
  },
  dev: {
    serverUrl,
  },
};

It works okay.

This is my tsconfig.json configuration:

"files": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path"": "./tsconfig.spec.json"
    }
    
  ],
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
     "strict": true,
     "resolveJsonModule": true,
     "esModuleInterop": true
     

    
  },

  
}

I've been stuck on this for several days now without any luck in finding a solution. Any help would be greatly appreciated. Thank you.

Answer №2

Recently encountered a similar issue and managed to uncover the solution on typescriptlang.org. The key is to activate the following option:

resolveJsonModule - Enables the importation of modules with a ‘.json’ extension, a common practice in node projects. This involves creating a type for the import based on the static JSON structure. By default, TypeScript does not have support for resolving JSON files.

To implement this, simply enable the option in your tsconfig.json within the compilerOptions section:

"files": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.spec.json"
    }
    
  ],
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
     "strict": true,
     "resolveJsonModule": true,
     "esModuleInterop": true,
     "resolveJsonModule": true
  },      
}

Additionally, you may also want to consider enabling allowSyntheticDefaultImports to prevent eslint errors.

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

Improving characteristics of an Observable Entity (Angular)

I have a question about Observables that I'm hoping someone can help me with. I am trying to work with an object that I want to turn into an Observable. Let's say the object is structured like this: export class Sample { public name: string; ...

The presence of this container with Mongoose Schema Typescript eclipses an external 'this' value

Here's my schema validator code for MongoDB: UserSchema.path('email').validate(async function (email: string) { const count = await User.count({ email, _id: { $ne: this._id } }) return !count }, 'Email already exists') However ...

Converting a JSON response into a Python variable

I have a question regarding the following code snippet (an HTML response). Do I need to remove the "M18.high_52 = {" at the beginning and the "}" at the end in order to assign it under a Python JSON variable? Thank you for your help! Update: I want to ext ...

The background image is excessively zoomed in on an actual iPad device

I'm having trouble figuring this out. My tech stack includes Next.js, TypeScript, and Chakra UI. When I inspect my application, everything looks great as intended. On mobile, it works perfectly fine. However, when I view it on my physical iPad withou ...

Issue with Angular build process

Upon running 'npm run dist' to build the ES2015 javascript bundles, I encountered an error (Exhibit 1) while no error occurred when using 'npm start -o'. The issue appears to be related to the Angular Material Autocomplete component (Ex ...

Angular Material square-shaped icon buttons

I utilize Angular Material for my UI, specifically for my buttons. My desired outcome is as follows: https://i.sstatic.net/w82Kt.png Although I prefer raised buttons with text labels and icons, I find that the raised buttons using the mat-raised-button c ...

In Bootstrap 4, the vertical group of buttons is aligned to the bottom

I am trying to align a group of buttons at the bottom, centered horizontally and aligned vertically. Currently, this is how it looks: <div class="row"> <div class="col-md-4"> <div class="center-block"> <div cla ...

Issue with iOS 10: Changes to class not reflected in CSS/styles

Currently, I am utilizing Ionic with Angular to develop an application for Android and iOS. Surprisingly, everything functions smoothly on Android, but there seems to be an issue with iOS. I am employing a class change on an element using ng-class. I can ...

Capture stunning photos with Ionic Capacitor CameraPreview, where the camera is always front and center. Say goodbye to any

I'm currently working on developing a customized camera feature for a tablet application. One of the challenges I'm facing is getting buttons to float over the camera preview. Despite setting the isBack attribute to true, the camera preview remai ...

Leverage the power of Angular 2 components within your Asp.net MVC

I am currently working on an Asp Mvc project which utilizes Angular 1.4 for the frontend. While my project is not designed to be a single page application, I am interested in incorporating Angular 2 without transitioning the entire project into a SPA. Aft ...

What is the proper way to incorporate generics into a function in TypeScript when you plan to call it using .call()?

interface Wrapped<T> { data: T; } interface BetterWrapper<T> { betterData: T; } function abc<T>(test: Wrapped<T>): BetterWrapper<T> { return {betterData: test.data} } const result = abc<string>.apply({}, { data: ...

The getText method needs to be invoked from the user interface thread

I am currently working on an Android application that requires sending data to a database. I have implemented JSONParser for this purpose. However, I encountered an issue where the application fails to send the data to the server. The error seems to be o ...

Tips for using jest toHaveBeenCalled with multiple instances

Currently, I am in the process of writing a test case for one of my functions. This function calls another function from a library, and I am attempting to mock this function (saveCall). Below is a snippet of the sample code in question: import { Call } fro ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Updating Data in Json Using VB.Net

(Apologies for my poor English skills.) Yesterday, I installed JSON.Net (Newtonsoft) and tried to familiarize myself with the documentation and examples provided. Despite my efforts, I am unable to achieve the desired results. Firstly, let me share a sni ...

Exploring Angular 2's @Input and @Output Directives

I'm unsure about whether I should be using @Input and @Output. From my understanding, these decorators are typically used when you want to establish communication between a parent and child component. Can you confirm or correct me on this? I have 3 c ...

"Effortlessly rearrange list items using drag-and-drop with the added convenience of

I am looking to populate a ListBox with items from JSON data retrieved dynamically from an Asp.Net and MySQL database. Despite finding code snippets online, none of them seem to be meeting my specific requirements. Although I do not encounter any errors, ...

After upgrading from Angular 7 to 12, the module './rest.service.interface' does not export 'RestService' (imported as 'RestService'), causing it to not be found

Hey everyone, I've been struggling with a problem for hours now and I can't seem to fix it. Here is the interface I'm working with: import { HttpClient } from '@angular/common/http'; import { Response } from '@angular/http&apo ...

Optimal method for efficiently caching data when toggling between list view and detail view within Angular 12

In my Angular App, I have implemented two components - a list view and a details view. Users can switch between these components, both of which utilize multiple async pipes. To minimize the number of http requests to the backend, I decided to cache data u ...

A new feature introduced in TypeScript, expression-level syntax was not present until it was added in JavaScript

Celebrating a Decade of TypeScript remarked that "It’s quite remarkable how the design goals set for TypeScript have stood the test of time." I am particularly intrigued by the goal of "Avoid adding expression-level syntax." One user even brought up thi ...