Typescript compiler error when importing json file

typescript import json file
typescript 3 import json
typescript absolute import
import json file in typescript angular
import a json file into typescript
typescript read json file into object
typescript import file
typescript read 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.

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.

Importing json files works but typescript compiler logs error · Issue , This code (or something similar): import localeEn from './locale-en.json!'; export default function translateSources() { let en = localeEn; } Works  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.

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'

Importing JSON Modules in TypeScript, TypeScript 2.9 introduced a new --resolveJsonModule compiler In Node, we can use a require call to import this JSON file like any With --​resolveJsonModule enabled, we no longer get a type error in our TypeScript file. JSON file is loaded and the translations properly recorded but the compiler stills outputs the message: logger.js:17 TypeScript Cannot find module './locale-en.json'. (TS2307)

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

Handbook - Module Resolution, First, the compiler will try to locate a file that represents the imported module. To do Finally, if the compiler could not resolve the module, it will log an error. In our example, if Node.js found the file /root/src/moduleB/package.json containing​  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:

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!

How to Import json into TypeScript, If you are using Typescript version 2.9, you don't need to follow solution 2. Here is how you can do it: In your `tsconfig.json` file, under compiler  Importing JSON Modules in TypeScript April 20, 2019. TypeScript 2.9 introduced a new --resolveJsonModule compiler option that lets us import JSON modules from within TypeScript modules. Importing JSON Modules via require Calls. Let's assume we have a Node application written in TypeScript, and let's say that we want to import the following JSON file:

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`

Typescript compiler error when importing json file, requiring: import json = require('calls.json'); None work properly and have their own little compiler errors :) I want to use an external .json file  Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.

How To Read Local JSON Files In Angular, We can import or read local JSON files in Angular,several different ways In typescript 2.9 with the help of resolveJsonModule we can import local To remove the above error,In tsconfig.json file under compiler options we  Or you can simply delete all of the duplicate typings from the typings folder. What's happening is that it's automatically importing all of the typings from the the node_modules folder of every import you do in your code. It's also importing the typings that are dependencies of the browser.d.ts file.

VSCode typescript importing json file highlighting issue, VSCode typescript importing json file highlighting issue - json. and esModuleInterop with the value of true to my compiler options to enable importing json within typescript. node_modules/bundle/bundle.d.ts Module build failed: Error:  tsconfig.json Overview # The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways: Using tsconfig.json #

TypeScript - Help, All the detected syntax and compilation errors are reported in the Errors and Compile passed to the TypeScript Language Service when the tsconfig.json file is not found. IntelliJ IDEA can generate import statements for modules, classes,  TypeScript 2.9, which was released in May 2018, introduced a new compiler option called resolveJsonModule. This allows you to import .json files and interpret the contents as a well-typed JavaScript Object - which means the compiler will recognise types like string, number and boolean.

Comments
  • This would work, though I am using requirejs clientside. This means when loading the requirejs definition, the declared var require in the node definition causes problems because a var require was also declared in require.d.ts...
  • Yup, that's expected when both definitions are referenced at once. That would also be the case at runtime too. You would never be using both require at the same time. The quick solution is to have that file not reference either of them and just use declare var require: any;.
  • @thoughtrepo Could elaborate on your answer? Typescript to Babel to ES5 is still looking for a module. I'm finding myself in that situation, and although the fail-safe intuition would be to import the json as var config = require('./config.json'), Typescript-Babel does still indicate the same 'cannot find module .config.json' error message.
  • I got the error "Failed to lint:: require statement not part of an import statement". Can someone please help?
  • import { default as data } from './data.ts';
  • @phi not sure the '.ts' extension is needed.
  • Doesn't work see this github issue
  • @Max works for me. The fix was merged into master on the 5th of Jul, now available in stable.
  • this only works if your target is commonjs, if you want to output anything else it won't work
  • requires unnecessary http request