Import json file in typescript Angular 5

落花浮王杯 提交于 2019-12-13 16:30:38

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/51541468/import-json-file-in-typescript-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!