Import static JSON file from assets dir in component (Angular)

Issue

I am using Angular CLI (version 6).
I have a small JSON file in my assets folder which I want to import into my component. I want to do this without using a GET request from my component.

What I did:

  • I created a new file, typings.d.ts:

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

    … and referred to it in tsconfig.spec.json. Here is a snippet of the referral in ts.config.spec.json:

    "files": [
        "test.ts",
        "polyfills.ts",
         "./typings.d.ts"
    ],
    
  • From my component, I am trying to import my JSON file as such:

    import * as myConfig from '../../assets/config.json';
    

At that line however, I get an error message: cannot find module ../../assets/config.json.

I am quite sure that this relative path is correct (I tried several other options as well, similarly for the typings.d.ts referral – but anyway, my directory structure is just a simple Angualr CLI app:

|- src
    |   
    |-app
    |   |-component
    |       |-component.ts
    |
    |
    |-assets
        |-config.json

Any tips on how to solve this problem would be greatly appreciated.

Solution

You can just import myConfig from 'path/to/json' then use it in your file.

Answered By – Efe

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.