Typescript compiler error when importing json file

JavascriptJsonnode.jsTypescriptCommonjs

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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!

Solution 3 - Javascript

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'

Solution 4 - Javascript

This can also be done by using import statement if using webpack v2 which is already packed with json-loader.

> Note that this is not async

import data from './data.json';//Note that this is not async

Also, in your typings.d.ts file add the following wildcard module to avoid typescript error saying: Cannot find module

declare module "*.json" {
    const value: any;
    export default value;
}

For anyone interested in async imports, check this article by 2uality

Solution 5 - Javascript

As of Typescript 2.9 you can import JSON file natively without any additional hack/loader needed.

The following excerpt is copied from said link above.

> ...TypeScript is now able to import JSON files as input files when using the node strategy for moduleResolution. This means you can use json files as part of their project, and they’ll be well-typed!

./src/settings.json

{
    "dry": false,
    "debug": 

./src/foo.ts

import settings from "./settings.json";

settings.debug === true;  // Okay
settings.dry === 2;       // Error! Can't compare a `boolean` and `number`

Solution 6 - Javascript

Year,2021. I wanted to import package.json version

For Angular folks, if you are stuck. Want to use import?

open tsconfig.json & add inside compilerOptions key

"resolveJsonModule": true,

That's it you can use it

import { version } from '../package.json';

Solution 7 - Javascript

For Angular 6 it can work with simple HTTP get call as below

Service
//interface, could be Array , object 
export interface ResultJSON{

}
 //Read JSON file for 3DWide
  getJSON() {
    return this.http.get(this.filepathUrl);
  }

Component :import both service and interface and use as below
resultJSON :ResultJSON;
 this
      .testService
      .getJSON()
      .subscribe((data: ResultJSON) => {
           this.resultJSON= data;
           console.log(this.resultJSON); 

         
         });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKenView Question on Stackoverflow
Solution 1 - JavascriptthoughtrepoView Answer on Stackoverflow
Solution 2 - JavascriptMatt BiernerView Answer on Stackoverflow
Solution 3 - JavascriptkenjuView Answer on Stackoverflow
Solution 4 - JavascriptsabithpockerView Answer on Stackoverflow
Solution 5 - JavascriptdoomleikaView Answer on Stackoverflow
Solution 6 - JavascriptminigeekView Answer on Stackoverflow
Solution 7 - Javascriptuser2112373View Answer on Stackoverflow