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:
add "resolveJsonModule": true
to the compilerOptions
in jsconfig.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]
To get data from a local JSON file, we need to import the file into the component where we want to process the data. We do the import just like we would with a component, except the component name is replaced with whatever we want to call the data set.
You should add
"resolveJsonModule":true
as part of compilerOptions to tsconfig.json.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With