3

I have a simple .json file outside of my project. Like this :

| common
    | configuration.json
| angular-app
    | src
        | app
            | my-component
                | my-component.component.ts
    | angular.json

In my-component.component.ts, i want to import configuration.json. I tried import configuration from '../../../../common.configuration.json' but Angular just keep throwing this error :

ERROR in src/app/record/record.component.ts(4,23): error TS2732: Cannot find module '../../../../common/configuration.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

And when i try ng serve --resolveJsonModule, i got this error : Unknown option: '--resolveJsonModule'

I can't move configuration.json. The common directory is shared with other projects.

How do you import a local json file in an Angular project ?

2
  • move your json file into assets directory. I faced same issue. Commented Sep 6, 2019 at 8:35
  • I can't move configuration.json, i edited my question. Commented Sep 6, 2019 at 8:37

3 Answers 3

6

If you're using typescript 2.9+ (Angular 6.1+), you can import JSON modules so it will get compiled into the application. Older version don't support this so that may be your issue.

All you need to do is make sure the following three compiler options are enabled in your tsconfig.json:

{
  ...
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
    ...
  }
}

Then you can import JSON modules in any TS file:

import jsonContents from '../../contents.json';
Sign up to request clarification or add additional context in comments.

Comments

3

Try by using http call:

this.http.get(`yourpath/..../common/configuration.json`).subscribe((resp: any) => {
   console.log(resp)
});

2 Comments

I don't want to expose my configuration.json file over http if possible.
If it is configuration file, it id better to have it in environment.ts
3

I'm not exactly sure what you mean but I guess you want to use the config values in your component, right?

According to this tutorial this can be fixed by creating a type definition file json-typings.d.ts in your app root folder with the following contents:

declare module "*.json" {
   const value: any;
   export default value;
}

1 Comment

In my case, this option fixed the issue. A good one!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.