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')
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 .
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.
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.
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:
declare module "*.json"
{
const value: any;
export default value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With