require a json file results in an error: Cannot find module

46.7k views Asked by At

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

There are 3 answers

1
gvlasov On

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.

0
egdfer On

You should add

"resolveJsonModule":true

as part of compilerOptions to tsconfig.json.

0
iwatachan On

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