How to use json file in typescript file

I have a file called men.json.

I want to make the equivalent of var men = require('./men.json'); .

No matter what I tried, it is looking for a ./men.json.js file.

I read that I can not use import , since it is not a ts file.

What is an equivalent string?

+6
source share
2 answers
 declare module '*.json' { var _: any; export default _; } 

then you can import mem from './mem.josn'

put this in some file that is included in tsconfig.json

now you can require .json , this works for any other file formats (although you need a web package since nodejs cannot require them directly)

+1
source

You should try the following:

 // foo.ts var mem = require('./mem.json); console.log(mem); 

Then compile ...

 tsc foo.ts 

This will give a generic typescript error, for example:

error TS2304: cannot find name 'require

which you could ignore ... or, preferably, get rid of by installing the necessary vise - or a package if you are using typescript 2 or later. (see typescript getting error TS2304: cannot find name 'require' )

0
source

Source: https://habr.com/ru/post/1013588/


All Articles