Joshua Ohana
Joshua Ohana

Reputation: 6121

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.

The error I'm getting is

Cannot find module './data.map.json'

I've checked the path 100 times it's definitely correct. 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.

Below is a clean minimal example showing my setup. How can I import a static json file in my Typescript application?

controller

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
}

Upvotes: 5

Views: 5732

Answers (2)

Matt Bierner
Matt Bierner

Reputation: 65175

The workaround may no longer be required since TS 2.9 added support for well typed json imports. Just add:

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

in your tsconfig.json or jsconfig.json. With this approach, you currently must use the full path with a .json file extension:

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

instead of:

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

Upvotes: 8

Joshua Ohana
Joshua Ohana

Reputation: 6121

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

Changed the import line to

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

and the file data.map.ts is

export default {
  "key": "value"
}

and you can access it just as you'd expect with

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

Upvotes: 0

Related Questions