Magus
Magus

Reputation: 15104

Import a local json file with Angular

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 ?

Upvotes: 3

Views: 8874

Answers (3)

Mark
Mark

Reputation: 811

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';

Upvotes: 6

mueslirieger
mueslirieger

Reputation: 181

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;
}

Upvotes: 3

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try by using http call:

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

Upvotes: 3

Related Questions