3

I am trying to import json file in typescript class like that

import * as nationalities from './mock/nationalities.json';

and it gives me an error

Cannot find module './mock/nationalities.json'.

and to solve this issue I added this

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

but it doesn't solve my issue and also gives my another error exception

Invalid module name in augmentation, module '*.json' cannot be found.

My Typescript version

2.9.2

4
  • "I added this" where? Commented Jul 26, 2018 at 14:40
  • possible duplicate of stackoverflow.com/questions/43275995/… Commented Jul 26, 2018 at 14:42
  • 1
    You probably added the declaration in the same file of the import, its a common mistake, just make sure that you add it in typings.d.ts Commented Jul 26, 2018 at 14:43
  • json files are not packaged by default, see step 1 in my answer below + import path should be absolute see step 3 Commented Jul 26, 2018 at 14:45

1 Answer 1

12

Based on this post, here is complete answer for Angular 6+:

Suppose you added your json files into "json-dir" directory:

  1. add "json-dir" into angular.json file :

    "assets": [
      "src/assets",
      "src/json-dir"
    ]
    
  2. allow import of json modules to prevent from typescript errors:

    Angular 6: add to typings.d.ts

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

    Angular 7+: add to tsconfig.json

    "compilerOptions": {
    ...
        "resolveJsonModule": true
    }
    
  3. from your controller, service or anything else, simply import the file by using this absolute path from /src directory. For example:

    import * as myJson from 'absolute/path/to/json/dir/json-file.json';

assuming source files are in src/app and json files in src/absolute/path/to/json/dir

Sign up to request clarification or add additional context in comments.

3 Comments

I followed these exact steps and its still throwing the same issue. Where elase could I need to add a config?
error TS2307: Cannot find module '../../../../../assets/data/countries.json'.
import path should be absolute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.