How do I read a local JSON file in Angular 12?

I am trying to read data from a local JSON file, that stores some config data for my app. I keep getting an error when using the ng build command in the Angular CLI.

The TypeScript file for my component: my-component.ts

...
import credentials from './config/credentials.json';

export class MyComponent implements OnInit {
    ...
    // Properties
    username: string = credentials.username;
    ...
}

The JSON config file, stored at the location '/config': credentials.json

{
    "credentials" : {
        "username" : "my_user_name",
        ...
    }
}

I am getting the error: Error: Should not import the named export 'credentials' (imported as 'credentials') from default-exporting module (only default export is available soon)

What is causing this error? It seems similar to the issue described here.

Upvotes: 1

Views: 7670

Answers (1)

There are two additional things you need to do for Angular version 12.

First, you need to add some lines to the file. Reference this question here. NOTE: these are different than Angular version 11.

{
    ...
        "compilerOptions": {
            ...
            "resolveJsonModule": true, // add this line...
            "esModuleInterop": true, // this line...
            ...
        },
    ...
    "allowSyntheticDefaultImports": true // and this line, notice this one is outside of "compiler options"
}

Second, you need to add a let statement. The above didn't work for me alone, but by also taking this step, I got it to work. Reference this blog post.

The TypeScript file for my component: my-component.ts

...
import credentials from './config/credentials.json';

let my_username = credentials.username;  // ADD THIS LINE

export class MyComponent implements OnInit {
    ...
    // Properties
    username: string = my_username; // NOW USE THE NEW VARIABLE
    ...
}

Admittedly I do not fully understand why this works, but it works. This source seems to suggest it has to do with variable scoping.

Upvotes: 3

Related Questions