Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compiler error when importing json file

So the code is simple:

calls.json

{"SERVER":{     "requests":{       "one":"1"     } } } 

file.ts

import json = require('../static/calls.json'); console.log(json.SERVER); 

the generated javascript is correct and when running the node js server, the console log json.SERVER prints '{ requests: { one: '1' } }', as it should.

The typescript compiler (commonjs) however, somehow does not particularly like this situation and throws: "Cannot find module '../static/calls.json'".

Ofcourse I tried writing a .d.ts file, like this:

declare module '../static/calls.json'{     var exp:any;     export = exp; } 

this then obviously throws: "Ambient module declaration cannot specify relative module name".

I also tried different variants, like:

declare module 'calls.json' {     import * as json from '/private/static/calls.json';     export = json; } 

and then requiring:

import json = require('calls.json'); 

None work properly and have their own little compiler errors :)

I want to use an external .json file because I use commonjs serverside and amd clientside and I want a single file for loading constants.

like image 706
Ken Avatar asked Oct 05 '15 14:10

Ken


People also ask

Where do you put resolveJsonModule?

Make sure to add these settings in the compilerOptions section of your tsconfig. json (documentation): You need to add --resolveJsonModule and --esModuleInterop behind tsc command to compile your TypeScript file.


2 Answers

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.

like image 153
thoughtrepo Avatar answered Sep 22 '22 15:09

thoughtrepo


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!

like image 33
Matt Bierner Avatar answered Sep 18 '22 15:09

Matt Bierner