Skip to content Skip to sidebar Skip to footer

Importing Static JSON In Create-react-app + Typescript

I am learning typescript and currently trying to import simple json file which I store locally in the project bootstrapped with create-react-app. data.json looks like this: { 'te

Solution 1:

Solution 1: You can create a new file named data.json.ts with this statement:

export default {your_json};

Then import:

import { default as data } from './path/data.json';

ref: https://github.com/frankwallis/plugin-typescript/issues/129

Solution 2: The problem here that when you compile your project (for example into a folder named lib) you don't have your .json file inside your lib folder. You simple can include that file into your build or manually copy that file into your lib folder. To import your file you have to use:

  • const data = require('data.json');
  • declare your own type. Create a new file named your_file_name.d.ts and stick into this file the following code:
declare module "*.json" 
{
    const value: any;
    export default value;
}

Solution 2:

Try to change the import to: import {test} from './data.json'. This works for me. If you want it named data you can change the name of test to data in the .JSON file. Or assign it to another variable after importing.


Post a Comment for "Importing Static JSON In Create-react-app + Typescript"