5

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

3 Answers 3

11

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"
Sign up to request clarification or add additional context in comments.

Comments

1

// 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,
    ....
  },

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.