简体   繁体   中英

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:

{
  "test": "123",
}

In my App.tsx I am trying to import it using json-loader . Both App.tsx and data.json are in the same folder and the import looks like this:

import data from './data.json'

I've already tried couple solutions to this problem but nothing seems to work. Those solutions are import * as data from './data.json' and const data = require('./data.json')

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM