How to Import json into TypeScript

Written by jecelynyeen | Published 2016/11/28
Tech Story Tags: javascript | typescript | json

TLDRvia the TL;DR App

In ES6/ES2015, you can import json file in your code. For example,

Given you have this example.json` file:

{"name": "testing"}

You could import it in ES6/ES2015 like this.

// ES6/ES2015// app.js

import * as data from './example.json';

const word = data.name;

console.log(word); // output 'testing'

In Typescript, however, the same code will throw error:

Cannot find module 'example.json'

[UPDATE] Solution: Typescript 2.9 supports JSON import!

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 options, add these two lines:

{"compilerOptions": {"resolveJsonModule": true,"esModuleInterop": true}}

Then you can import json like this:

// Typescript// app.ts

import data from './example.json';

const word = (<any>data).name;

console.log(word); // output 'testing'

Easy Peasy!

Solution: Using Wildcard Module Name

In Typescript version 2 +, we can use wildcard character in module name. In your TS Definition file, e.g. typings.d.ts`, you can add this line:

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

Then, your code will work like charm!

// Typescript// app.ts

import * as data from './example.json';

const word = (<any>data).name;

console.log(word); // output 'testing'

Sample code here: https://github.com/chybie/ts-json

This solution works well with Angular project too.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Published by HackerNoon on 2016/11/28