Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')

like image 992
Dimitry Ivashchuk Avatar asked Sep 13 '18 19:09

Dimitry Ivashchuk


People also ask

How do I import json into React app?

To import JSON file in React, we use import to import it like a regular module. import Profile from "./components/profile"; to import the ./components/profile JSON file as Profile . This works because the json-loader Webpack module is included with create-react-app .

Can we use TypeScript in Create React app?

Create react app is basically a node package that we can simply install. The interesting part about this is that you can use it with TypeScript very easily by leveraging the use of npm or yarn depending on what your package manager preference is.

Is create React app static?

create-react-app 's build does not prebuild any of your DOM. It generates a blank canvas, and the JavaScript bundle builds the DOM for your client. Like Gatsby, these files are static and do not require server-side execution to run. It does not require NodeJS.


1 Answers

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;
}
like image 179
Nikolay Vetrov Avatar answered Sep 30 '22 05:09

Nikolay Vetrov