【问题标题】:Importing JSON file in Node Typescript在 Node Typescript 中导入 JSON 文件
【发布时间】:2018-05-14 22:29:54
【问题描述】:

我已经尝试了网上找到的所有解决方案,但似乎无法解决我的具体问题。

我正在尝试将静态 .json 文件导入节点控制器,全部在 TypeScript 中。

我得到的错误是

找不到模块'./data.map.json'

我已经检查了 100 次路径,它绝对是正确的。我已经尝试过 require 与 import 的每种组合,以及我可以在 tsconfig.json 中找到的每个选项,我认为这就是问题所在。

下面是一个简洁的示例,展示了我的设置。如何在我的 Typescript 应用程序中导入静态 json 文件?

控制器

import * as data from "./data.map.json";

typings.d.ts

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

tsconfig.json

{
  "compilerOptions": {
    "outDir": "build",
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "typeRoots": ["node_modules/@types"],
    "paths": {
      "*": ["typings.d.ts"]
    }
  },
  "files": [
    "typings.d.ts"
  ],
  "include": [
    "src/**/**.ts",
    "test/**/**.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false
}

【问题讨论】:

    标签: json node.js typescript


    【解决方案1】:

    自 TS 2.9 added support for well typed json imports 起,可能不再需要该解决方法。只需添加:

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

    在您的tsconfig.jsonjsconfig.json 中。使用这种方法,您目前必须使用带有.json 文件扩展名的完整路径:

    import * as data from "./data.map.json";
    

    代替:

    import * as data from "./data.map";
    

    【讨论】:

      【解决方案2】:

      前段时间解决了这个问题,忘了在这里发布答案。我没有尝试导入 json 文件,而是从 typescript 文件中导出一个 json 对象,效果很好

      将导入行改为

      import {default as map} from "./data.map";
      

      文件data.map.ts

      export default {
        "key": "value"
      }
      

      您可以按照您的预期访问它

      map["key"]   // gives you "value"
      

      【讨论】:

      • 我记得在 TypeScript 教程中这样做过,但是查看 typescriptlang.org/docs/handbook/… 暗示只有 SystemJS 和 AMD 等加载器支持这种类型的类型。从您的代码中您使用 CommonJS
      • 这不是在加载 JSON 文件。它只是加载一个 javascript 对象。
      猜你喜欢
      • 2018-10-04
      • 2020-11-22
      • 2020-06-02
      • 2019-12-11
      • 2018-07-17
      • 2020-01-13
      • 1970-01-01
      • 2018-04-10
      相关资源
      最近更新 更多