如何在 React 的根目录中使用 config.json?
How use a config.json in root directory with React?
我想使用位于 React 根目录中的 config.json 文件。这是因为我需要更新这个文件 json whitout 重建项目。
项目结构:
> /build
> /node_modules
> /public
> /src
> config.json
> package.json
...ect.
我尝试了什么?
[尝试 1] 从根目录导入..
import { configUrl } from "./../../config.json";
[尝试2]加入依赖项
"@project-name": "file:./config.json"
并导入react组件
import { configUrl } from "@project-name";
最终使用 fetch:
return fetch(configUrl, requestOptions)
.then((response) => response.json())
.then((result) => {
console.log(result);
return result;
})
.catch((error) => console.log("error", error));
但是没有人工作,我还能做什么?
你可以做的一件事是将你的 config.json
文件放在你的 React 应用程序根目录的 public 文件夹中,然后在你的应用程序的最顶层组件中获取它。
async function getConfig {
const res = await fetch('/config.json');
const config = res.json();
}
'/config.json'
这个 url 会起作用,因为所有未识别的端点都被重定向到 public 文件夹。
注意:如果您的 React 应用程序是托管的,它将允许任何人使用上述 url.
访问您的配置文件
我想使用位于 React 根目录中的 config.json 文件。这是因为我需要更新这个文件 json whitout 重建项目。
项目结构:
> /build
> /node_modules
> /public
> /src
> config.json
> package.json
...ect.
我尝试了什么?
[尝试 1] 从根目录导入..
import { configUrl } from "./../../config.json";
[尝试2]加入依赖项
"@project-name": "file:./config.json"
并导入react组件
import { configUrl } from "@project-name";
最终使用 fetch:
return fetch(configUrl, requestOptions)
.then((response) => response.json())
.then((result) => {
console.log(result);
return result;
})
.catch((error) => console.log("error", error));
但是没有人工作,我还能做什么?
你可以做的一件事是将你的 config.json
文件放在你的 React 应用程序根目录的 public 文件夹中,然后在你的应用程序的最顶层组件中获取它。
async function getConfig {
const res = await fetch('/config.json');
const config = res.json();
}
'/config.json'
这个 url 会起作用,因为所有未识别的端点都被重定向到 public 文件夹。
注意:如果您的 React 应用程序是托管的,它将允许任何人使用上述 url.
访问您的配置文件