Typescript compiler error when importing json file
Use var
instead of import
.
var json = require('./calls.json');
You're loading a JSON file, not a module, so import
shouldn't be used is this case. When var
is used, require()
is treated like a normal function again.
If you're using a Node.js definition, everything should just work, otherwise require
will need to be defined.
TS 2.9 added support for well typed json imports. Just add:
{ "compilerOptions": { "resolveJsonModule": true }}
in your tsconfig.json
or jsconfig.json
. Now imports such as:
import json = require('../static/calls.json');
and
import * as json from '../static/calls.json';
should be resolved and have proper typings too!
Another solution is to change data.json
to data.ts
and export like this
export default { "key" : { ... }}
and import as you would expect:
import { default as data } from './data'