7

I have a file called men.json.

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

Whatever I have tried it looks for ./men.json.js file.

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

What is the equivalent required line?

vpibano
  • 2,415
  • 1
  • 13
  • 26
reza
  • 5,972
  • 15
  • 84
  • 126

2 Answers2

2
declare module '*.json' {
    var _: any;
    export default _;
}

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

put this into some file that's included in tsconfig.json

now you can require .json, this works for any other file formats (though you need webpack since nodejs cannot require them directly)

Qiaosen Huang
  • 1,093
  • 1
  • 10
  • 25
0

You should try requiring as follows:

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

Then compile ...

tsc foo.ts

This will give a generic typescript error, like:

error TS2304: Cannot find name 'require

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

Community
  • 1
  • 1
chriskelly
  • 7,526
  • 3
  • 32
  • 50