首页 > 解决方案 > 在 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 数据,我应该怎么做?

提前感谢您的宝贵时间。

标签: jsontypescriptvisual-studio-codetsconfig

解决方案


尝试使用模块。查看此文档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;
}

推荐阅读