构建应用程序后创建反应应用程序配置文件

create react app Configuration file after build app

我想在构建后在根文件夹中创建一个配置文件 (JSON) 来配置我的应用程序。

喜欢TranslationAPI Urls和...

我可以用 create react app 做到这一点吗?

src 目录外创建 config.jsjson 文件并将其包含在 index.html 中,如

<script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>

config.js

配置参数

config.js

var BASE_URL = "http://YOUR-URL";

你可以获得像

这样的参数
const BASE_URL = window.BASE_URL;

您可以将 JSON 文件存储在 public/ 文件夹中,它会在您托管 Create React 应用程序时自动提供此文件。

类似于:/public/my-configuration-file.json

然后当您重新启动应用程序时:

localhost:3000/my-configuration-file.json

将为您提供此 json 文件。

您可以创建一个自定义挂钩,使用 fetch 读取“public”配置文件。

// This path is relative to root, e.g. http://localhost/config.json
const configFile = './config.json'

export function useConfig() {
    const [config, setConfig] = useState(initialConfig);

    useEffect(() => {
        (async function fetchConfig() {
            try {
                const response = await (await fetch(configFile)).json();
                setConfig(response);
            } catch (e) {
                console.log(e);
            }
        }());
    }, []);

    return config;
}

然后在您应用的任何地方使用它

function App() {

    const config = useConfig();

    return (
        <div>{config.foo}</div>
    );
}

您将始终拥有最新的 non-cached 版本数据。