I am new to typescript.In my project we are using typescript2, In one of my requirement i need to import json file. so i have created .d.ts file as follows
test.d.ts
declare module "*.json" {
const value: any;
export default value;
}
i have included this definition in my tsconfig.json and importing to my ts file as follows
test.ts
//<refrence path="./test.json"/>
import * as data from './test.json';
when i am building my code i am getting following error
Cannot find module './test.json'
Note:- i don't want to use Requirejs
Thanks
I am new to typescript.In my project we are using typescript2, In one of my requirement i need to import json file. so i have created .d.ts file as follows
test.d.ts
declare module "*.json" {
const value: any;
export default value;
}
i have included this definition in my tsconfig.json and importing to my ts file as follows
test.ts
//<refrence path="./test.json"/>
import * as data from './test.json';
when i am building my code i am getting following error
Cannot find module './test.json'
Note:- i don't want to use Requirejs
Thanks
Share Improve this question asked Feb 21, 2018 at 16:37 user7789076user7789076 7983 gold badges12 silver badges25 bronze badges 3 |3 Answers
Reset to default 19With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:
import testJson from './test.json';
console.log(testJson.yourPropertyName);
Make sure to add these settings to your tsconfig.json:
"resolveJsonModule": true,
"esModuleInterop": true,
If you need the data to be recognised as a specific class, you can do that after import with as
, for instance:
const typedData = testJson as MyType[]
I handled that using a .ts with the json data in a variable:
import { data } from './jsonData'; // jsonData.ts
And the jsonData.ts would be like that:
export var data = {
"key": "value",
"key2": "value2"
}
Following this great article and depending on the TypeScript version you are using, you can follow the other 2 answers.
The case that is missing from them is when you are using TypeScript 2+. In this case, if you have a json
file like this:
{
"name": "testing"
}
you should add the following in the typings.d.ts
file:
declare module "*.json" {
const value: any;
export default value;
}
And then import the json
file as follows:
import * as data from './example.json';
const word = (<any>data).name;
console.log(word); // output 'testing'
/// <reference path="test.d.ts" />
before the import to basically enforce thattest.ts
uses that declaration file. Seems to work for me – Thomas Commented Feb 21, 2018 at 18:14