在打字稿Angular 5中导入json文件 [英] Import json file in typescript Angular 5

查看:32
本文介绍了在打字稿Angular 5中导入json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在这样的打字稿类中导入 json 文件

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

它给了我一个错误

<块引用>

找不到模块./mock/nationalities.json".

为了解决这个问题,我添加了这个

声明模块 '*.json' {常量值:任何;导出默认值;}

但它没有解决我的问题,也给了我另一个错误异常

<块引用>

扩充中的模块名称无效,找不到模块*.json".

我的打字稿版本

<块引用>

2.9.2

解决方案

基于此 post,这里是 Angular 6+ 的完整答案:

假设您将 json 文件添加到json-dir"目录中:

  1. 将json-dir"添加到 angular.json 文件中:

    资产":["来源/资产",src/json-dir"]

  2. 允许导入 json 模块以防止打字稿错误:

    Angular 6:添加到 typings.d.ts

    声明模块*.json"{常量值:任何;导出默认值;}

    Angular 7+:添加到 tsconfig.json

    "compilerOptions": {..."resolveJsonModule": 真}

  3. 从您的控制器、服务或其他任何东西,只需使用 /src 目录中的这个绝对路径导入文件.例如:

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

<块引用>

假设源文件在 src/app 中,json 文件在 src/absolute/path/to/json/dir

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

解决方案

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

这篇关于在打字稿Angular 5中导入json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆