Moody
Moody

Reputation: 833

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

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:

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.

Upvotes: 13

Views: 30937

Answers (3)

Radim Šafrán
Radim Šafrán

Reputation: 598

The easiest way is:

  1. Give the structure a name (json, xml, whatever) :

    export const myJson = { "_id":"1234", "name":"John" }

  1. Change the file extension to ".ts"

  2. Finally import the file

    import { myJson } from 'src/my-static-file';

    public json = myJson;

Upvotes: 3

Adam
Adam

Reputation: 133

The new file you added should be named json-typings.d.ts with the following code:

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

Put it in your src folder (the same directory as index.html)

Then import JSON files in your component:

import * as SampleJson from "../../assets/SampleJson.json";

Also, you don't need to refer to it in ts.config.spec.json

Upvotes: 2

Efe
Efe

Reputation: 5796

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

Upvotes: 9

Related Questions