Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 534
Joshua Ohana Avatar asked Nov 30 '17 21:11

Joshua Ohana


1 Answers

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";
like image 191
Matt Bierner Avatar answered Oct 11 '22 08:10

Matt Bierner