5

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
}
0

2 Answers 2

8

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";
Sign up to request clarification or add additional context in comments.

Comments

0

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"

2 Comments

I remember doing this from a TypeScript tutorial, However looking at the typescriptlang.org/docs/handbook/… it hints that only loaders such as SystemJS and AMD support this type of typing. From your code your using CommonJS
This isn't loading a JSON file however. It just loads a javascript object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.