简体   繁体   English

在Node Typescript中导入JSON文件

[英]Importing JSON file in Node Typescript

I have tried every solution found online but it seems I cannot get my specifics resolved. 我已经尝试过在网上找到的所有解决方案,但似乎我无法解决我的具体问题。

I am trying to import a static .json file into a node controller, all in TypeScript. 我试图将静态.json文件导入节点控制器,所有这些都在TypeScript中。

The error I'm getting is 我得到的错误是

Cannot find module './data.map.json' 找不到模块'./data.map.json'

I've checked the path 100 times it's definitely correct. 我已经检查了100次路径,这绝对是正确的。 I have tried every combination of require vs import, and every option I could find in tsconfig.json, which is where I believe the problem lies. 我已经尝试了require和import的每个组合,以及我在tsconfig.json中找到的每个选项,这是我认为问题所在。

Below is a clean minimal example showing my setup. 下面是一个简洁的示例,显示了我的设置。 How can I import a static json file in my Typescript application? 如何在Typescript应用程序中导入静态json文件?

controller 调节器

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

typings.d.ts typings.d.ts

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

tsconfig.json 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
}

The workaround may no longer be required since TS 2.9 added support for well typed json imports . 由于TS 2.9 增加了对良好类型的json导入的支持,因此可能不再需要解决方法。 Just add: 只需添加:

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

in your tsconfig.json or jsconfig.json . 在你的tsconfig.jsonjsconfig.json With this approach, you currently must use the full path with a .json file extension: 使用此方法,您当前必须使用带有.json文件扩展名的完整路径:

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

instead of: 代替:

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

Fixed this a while ago forgot to post the answer on here. 修复了这一段时间之前忘了在这里发布答案。 Instead of trying to import a json file I just export a json object from a typescript file and it works great 我没有尝试导入json文件,而只是从typescript文件中导出json对象,而且效果很好

Changed the import line to 将导入行更改为

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

and the file data.map.ts is data.map.ts文件是

export default {
  "key": "value"
}

and you can access it just as you'd expect with 你可以像你期望的那样访问它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM