I want to use a config.json file located in root directory in React. The reason of this is because i will need update this file json whitout rebuild project.
Project estructure:
> /build
> /node_modules
> /public
> /src
> config.json
> package.json
...ect.
What i try?
[Try 1] Import from root directory..
import { configUrl } from "./../../config.json";
[Try 2] Add into dependencies
"@project-name": "file:./config.json"
And import into react component
import { configUrl } from "@project-name";
To finally use fetch:
return fetch(configUrl, requestOptions)
.then((response) => response.json())
.then((result) => {
console.log(result);
return result;
})
.catch((error) => console.log("error", error));
But noone work, what more can i do?
CodePudding user response:
One thing you can do is to put your config.json
file in public folder in the root dir of your React app and then fetch it in the top most component of your app.
async function getConfig {
const res = await fetch('/config.json');
const config = res.json();
}
'/config.json'
This url will work because all unidentified endpoints are redirected to public folder.
CAUTION: If your react app is hosted it will let anyone access your config file with above url.