用于部署后设置的 React 配置文件 [英] React configuration file for post deployment settings

查看:72
本文介绍了用于部署后设置的 React 配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个 reactjs 站点并试图让它可以部署.

I've built a reactjs site and trying to get it to be deployable.

现在所有的配置都是通过一个 config.js 完成的,它被导入到所有模块中.

right now all configuration is done via a config.js which is imported into all modules.

但是当我构建应用程序时,它会被编译到部署 js 中并且不可配置.

But when I build the app, this gets compiled into the deployment js and isn't configurable.

我想要一个单独的文件,系统管理员可以配置特定于他们环境的各种设置,例如 API 端点(应用程序可能不会与后端在同一服务器上运行,并且不会有任何访问 DNS).

I want to have a separate file which a sys admin can configure various settings specific to their enviroment, such as the API end points (the app may not be running on the same server as the backend, and there will not be any access to DNS).

有没有办法在反应中做到这一点?我也不希望为此使用 3rd 方库.

Is there a way to do this in react? I do not wish to use 3rd party libraries for this either.

推荐答案

我设法找到了一个解决方案.

I've managed to hack together a solution.

在公共文件夹config.js"中

in the public folder 'config.js'

var config = {
      x: 'y',
};

接下来包装 ReactDOM.render(App/index.js 像这样的功能

Next wrap the ReactDOM.render (App/index.js in a fucntion like so

window.RenderApp = (config) => {
   ReactDOM.render(<App _config={config}/>, document.getElementById('root'));
}

在 index.html 中添加这些行,window.RenderApp 必须在最后,因为它依赖于 bundle.js 被导入,它由 react 自动添加并且在生产中具有随机名称.

In the index.html add these lines, the window.RenderApp HAS to be at the end, because it relies on bundle.js being imported which is auto added by react and has a random name in production.

</html>
...
<head>
...
<script type="text/javascript" src="%PUBLIC_URL%/config.js"></script>
...
</head>
...
<body>
...
</body>
<script>
   window.RenderApp(config);
</script>
</html>

最后在你的 App.js 中使用配置变量或者你叫它什么

lastly to use the config variables in your App.js or what ever you called it

...
constructor(props) {
    super(props)
    console.log(this.props._config)
    this.state = {
       ....
       config: this.props._config,
   }
}
...

我发现您必须将 config 设置为状态变量,否则它会为对象随机抛出 undefined,现在只需将 config 传递到层次结构中即可在您的代码中使用.

I found you have to set config to a state variables or else it will randomly throw undefined for the object, now just pass config down the hierarchy to use in your code.

这篇关于用于部署后设置的 React 配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆