简体   繁体   English

在打字稿中导入json

[英]Import json in typescript

I am new to typescript.In my project we are using typescript2, In one of my requirement i need to import json file. 我是typescript的新手。在我的项目中我们使用typescript2,在我的一个要求中我需要导入json文件。 so i have created .d.ts file as follows 所以我创建了.d.ts文件如下

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

i have included this definition in my tsconfig.json and importing to my ts file as follows 我已将此定义包含在我的tsconfig.json中并导入到我的ts文件中,如下所示

  test.ts
//<refrence path="./test.json"/>
import * as data from './test.json';

when i am building my code i am getting following error 当我构建我的代码时,我得到以下错误

Cannot find module './test.json'

Note:- i don't want to use Requirejs 注意: - 我不想使用Requirejs

Thanks 谢谢

With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this: 使用TypeScript 2.9。+,您只需导入类型安全和智能感知的JSON文件,如下所示:

import testJson from './test.json';
console.log(testJson.yourPropertyName);

Make sure to add these settings to your tsconfig.json: 确保将这些设置添加到tsconfig.json:

"resolveJsonModule": true,
"esModuleInterop": true,

I handled that using a .ts with the json data in a variable: 我使用.ts和变量中的json数据来处理:

import { data } from './jsonData'; // jsonData.ts

And the jsonData.ts would be like that: 而jsonData.ts就是这样的:

export var data = {
  "key": "value",
  "key2": "value2"
}

Following this great article and depending on the TypeScript version you are using, you can follow the other 2 answers. 按照这篇伟大的文章并根据您使用的TypeScript版本,您可以按照其他2个答案。

The case that is missing from them is when you are using TypeScript 2+. 他们缺少的情况是您使用TypeScript 2+时。 In this case, if you have a json file like this: 在这种情况下,如果你有一个像这样的json文件:

{
    "name": "testing"
}

you should add the following in the typings.d.ts file: 你应该在typings.d.ts文件中添加以下内容:

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

And then import the json file as follows: 然后导入json文件,如下所示:

import * as data from './example.json';

const word = (<any>data).name;

console.log(word); // output 'testing'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM