Importing JSON files in Typescript

Tamás Polgár
Developer rants
Published in
1 min readAug 9, 2020

A simple trick to retire require() and also get rid of complicated file loading.

First add this to your tsconfig.json:

"compilerOptions": {
"resolveJsonModule": true
},
..."include": [
"src/**/*.json",
]

This is assuming your source code is in the src directory, as it normally should be.

Now you can import any JSON file like this:

import * as magic from './myLittlePony.json';

Typescript will automagically convert your JSON into a module. To access its content you’ll have to look into its default property:

var pony = magic.default.ponies[0]

--

--