40

In a nodej project open in VsCode with checkJs enabled, when a json file is required like

const myFile = require('./my-file.json')

This makes an error [ts] Cannot find module.

How is it possible to remove the error warning?

I tried to:

  1. add "resolveJsonModule": true to the compilerOptions in jsconfig.json, but it does not work.

  2. create a typing.d.ts file with this content:

    declare module '*.json' { const value: any; export default value; } But now, there is an error [ts] Type 'typeof import("*.json")' must have a '[Symbol.iterator]()' method that returns an iterator. [2488]

3
  • 1
    You don't need to specify json extension when you do a require. const myFile = require('./my-file'); Commented Nov 15, 2018 at 13:08
  • 1
    Thanks but there is the same error if there is no extension. The error shows up because the json file is not a module. (-> it has no module.exports) Commented Nov 15, 2018 at 13:13
  • Check this answer, maybe that it can help you : stackoverflow.com/questions/49996456/… Commented Nov 15, 2018 at 13:18

3 Answers 3

22

You should add

"resolveJsonModule":true

as part of compilerOptions to tsconfig.json.

Sign up to request clarification or add additional context in comments.

1 Comment

No, this doesn't remove the error, and OP also stated that in his question
21

I had a similar problem when trying to import json from a file in a typescript project.

I used

import * as data from "module/path/filename.json"

instead of

const data = require("module/path/filename.json")

and it worked.

1 Comment

This just gives me "Cannot use import statement outside a module"
1

In my case, I had specified outDir and needed to put the json file at the output destination.

Comments

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.