如何将JSON文件导入TypeScript文件? [英] How to import JSON File into a TypeScript file?

查看:656
本文介绍了如何将JSON文件导入TypeScript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular Maps构建地图应用程序,并希望导入JSON文件作为定义位置的标记列表.我希望将此JSON文件用作app.component.ts中的marker []数组.而不是在TypeScript文件中定义标记的硬编码数组.

I am building a map application using Angular Maps and want to import a JSON file as a list of markers defining locations. I'm hoping to use this JSON file as marker[] array inside the app.component.ts . Instead of defining a hardcoded array of markers inside the TypeScript file.

导入此JSON文件以在我的项目中使用的最佳过程是什么?任何方向都非常感谢!

What is the best process of importing this JSON file for use in my project? Any direction greatly appreciated!

推荐答案

Aonepathan的单行代码一直为我工作,直到最近的打字稿更新为止.

Aonepathan's one-liner was working for me until a recent typescript update.

我发现Jecelyn Yeen的帖子,建议将此代码段发布到您的TS定义中文件

I found Jecelyn Yeen's post which suggests posting this snippet into your TS Definition file

将文件typings.d.ts添加到具有以下内容的项目的根文件夹中

add file typings.d.ts to the project's root folder with below content

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

,然后像这样导入您的数据:

and then import your data like this:

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

Typescript 2.9(文档)介绍了一种更好,更智能的解决方案.步骤:

Typescript 2.9 (docs) introduced a better, smarter solution. Steps:

  1. tsconfig.json文件中的此行添加resolveJsonModule支持:
  1. Add resolveJsonModule support with this line in your tsconfig.json file:

"compilerOptions": {
    ...
    "resolveJsonModule": true
  }

导入语句现在可以假定默认导出:

the import statement can now assumes a default export:

import data from './example.json';

和intellisense现在将检查json文件,以查看是否可以使用Array等方法.很酷

and intellisense will now check the json file to see whether you can use Array etc. methods. pretty cool.

这篇关于如何将JSON文件导入TypeScript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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