Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  65] [ 3]  / answers: 1 / hits: 5300  / 3 Years ago, thu, june 3, 2021, 12:00:00

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.


More From » json

 Answers
2

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.


[#1278] Friday, May 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackennamelissac

Total Points: 110
Total Questions: 118
Total Answers: 103

Location: Sweden
Member since Sun, Jan 16, 2022
2 Years ago
mackennamelissac questions
;