Angular environment.ts problem JSON. However environment.prod.ts

Viewed 195

I have problem importing json files into typescript. I have configured tsconfig.json according to the convention, but it still does not work in the environment.ts file, however in the environment.prod.ts file, the import works perfectly

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 module with '.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,
  },
};

Its work ok.

My tsconfig.json

"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 am several days, without finding why. Thank you.

2 Answers

Here you can see the error. Now mark it in console, but not in the file.

enter image description here

Just faced a similar problem and found the solution on typescriptlang.org. You need to enable following option:

resolveJsonModule - Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. This includes generating a type for the import based on the static JSON shape. TypeScript does not support resolving JSON files by default.

So enabling this option in you tsconfig.json under compilerOptions should do the job:

"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
  },      
}

Maybe you also need to enable allowSyntheticDefaultImports to avoid eslint errors.

Related