require a json file results in an error: Cannot find module
23,786
Solution 1
You should add
"resolveJsonModule":true
as part of compilerOptions to tsconfig.json.
Solution 2
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.
Related videos on Youtube
Comments
-
François Romain almost 2 years
In a nodej project open in VsCode with
checkJs
enabled, when a json file is required likeconst 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:
add
"resolveJsonModule": true
to thecompilerOptions
injsconfig.json
, but it does not work.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]
-
Thomas Lefetz over 5 yearsYou don't need to specify json extension when you do a require. const myFile = require('./my-file');
-
François Romain over 5 yearsThanks 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 nomodule.exports
) -
Thomas Lefetz over 5 yearsCheck this answer, maybe that it can help you : stackoverflow.com/questions/49996456/…
-
AlxVallejo about 2 yearsThis just gives me "Cannot use import statement outside a module"