josiah speed
josiah speed

Reputation: 51

How to import .json file with typescript React App

I'm getting the error:

Cannot find module '../public/data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.

import "./styles.css";
import data from "../public/data.json"; 
/**
 *
 * Welcome to the DDS coding challenge.
 *
 * Load `/public/data.json` as if it were a GET endpoint
 * and render it in a table using `/public/table.png` design.
 *
 * Make this behaviour reusable.
 *
 * Ask questions & have fun!
 *
 */
export default function App() {
  return <div className="App"></div>;
}

Here's a link to the challenge -> https://codesandbox.io/s/staging-snow-vvmvd?file=/src/App.tsx

enter image description here

Upvotes: 5

Views: 7038

Answers (3)

Ghazaleh Javaheri
Ghazaleh Javaheri

Reputation: 2117

you can do import and define type of imported data at same time e.g

const filters: {[key: string]: any} = require('./filters.json');

Upvotes: 0

Jahnavi Sananse
Jahnavi Sananse

Reputation: 118

// data.json:
{
"greeting" : "xin chao Vietnam"
}
// component:
import * as data from 'data.json';
let greeting = data.greeting;
//registering jsonModule in tsconfig.json
"compilerOptions": {
    ....
    "resolveJsonModule": true,
    ....
  },

Upvotes: 1

Stephen Jennings
Stephen Jennings

Reputation: 13234

The error message is letting you know that TypeScript cannot import JSON by default, you must enable the compiler option resolveJsonModule first. To do it in a React project, add the following to your tsconfig.json:

{
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

Next, when you import the JSON file, you must give it a path relative to the current file. The JSON file is going to be bundled with your JavaScript, so it should probably go in the /src directory instead of the /public directory. For example, if you put it in the same directory as App.tsx, then you would import it like so:

import data from "./data.json"

Upvotes: 11

Related Questions