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

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

问题描述

我正在使用 Angular Maps 构建一个地图应用程序,并且想要导入一个 JSON 文件作为定义位置的标记列表.我希望将此 JSON 文件用作 app.component.ts 中的标记 [] 数组.而不是在 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 的 one-liner 一直在为我工作,直到最近的打字稿更新.

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

我发现 Jecelyn Yeen 的 post 建议将此代码段发布到您的 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 (docs) 引入了更好、更智能的解决方案.步骤:

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
  }

import 语句现在可以假设默认导出:

the import statement can now assumes a default export:

从'./example.json'导入数据;

和智能感知现在将检查 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天全站免登陆