Import json file in typescript Angular 5

后端 未结 1 1280
渐次进展
渐次进展 2021-01-23 06:15

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

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

and it gives me an

相关标签:
1条回答
  • 2021-01-23 06:28

    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

    0 讨论(0)
提交回复
热议问题