json - 在 Typescript 中导入 Json 文件:终端出错
问题描述
我是打字稿的新手,我有 2 个问题。
一个。我想在 Visual Studio 代码(3.6.2)编辑器中使用以下代码在我的打字稿(main.ts)中导入一个简单的 JSON 文件:
import test from "./test.json";
console.log(test.name);
我也试过import * as test from "./test.json";
而 JSON 文件 (test.json) 如下:
{"name": "testing",
"age":25}
但是,当我输入“test.”时,typescript 会给出“name”、“age”作为属性的选项。
tsconfig.json 文件如下:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
此代码引发以下错误:
Cannot find module './test.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
由于类型定义是针对旧版本的,所以我没有使用它。我的打字稿版本是 3.6.3。上面提到的 3 个文件在同一个文件夹中。
-testfolder
- main.ts
- tsconfig.json
- test.json
虽然还有一些其他类似的问题,但我在我的代码中找不到问题!我也用 submile text 3 测试了它,但它也给出了同样的错误!
湾。如果我想从文件扩展名不同的文件(不是 .json)中解析 json 数据,我应该怎么做?
提前感谢您的宝贵时间。
解决方案
尝试使用模块。查看此文档https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html
// index.ts
import file from "./file.json";
console.log(file);
console.log(file.name);
// json.dt.ts
declare module "*.json" {
const file: any;
export default file;
}
推荐阅读
- c# - 如何使用 Openxml 替换 Word 文档中的文本
- amazon-web-services - 从 AWS api 网关获取“502 Bad Gateway”
- rest - Symfony 5 Rest,Base64 编码文件到 DTO,验证为 File 对象
- postgresql - 为什么我无法安装、删除或升级 postgresql 软件包?
- javascript - 未捕获的 DOMException:无法在“节点”上执行“replaceChild”:要替换的节点不是该节点的子节点
- python - 预处理数据集中的参数问题
- installation - 如何从 InstallShield Suite/高级 UI 设置的日志中隐藏输入的密码值
- c# - 反序列化具有不同标签的 XML 相同项目
- python - Python - 读取文件后数据未附加到列表和缺少字典键
- google-cloud-platform - 如何解决谷歌云实例问题