如何在 react jsx 中拥有一个外部 JSON 配置文件



我想在我的基于 React 的项目中有一个外部配置文件 (JSON(。这是最终结果,或者当我交付它(公用文件夹和捆绑包.js(时,也应该给出我的配置文件。用户应该能够根据自己的意愿更改配置并使用我的应用程序。它在那里,无需重新编译我的代码,应该能够使用它。换句话说,配置文件不应该与我的应用程序捆绑在一起。

接受的答案可能有效。但是,为什么要让它变得如此复杂?

步骤#1。创建包含内容的文件 Config.js

var Configs = {
    prop1 = "abc",
    prop2 = "123"
}

步骤#2。通过脚本标记.html在索引中加载文件。

<div id='root'></div>
<script src="Config.js"></script>
<script src="dist/bundle.js"></script></body>

步骤#3。只需直接在任何 React 组件中访问该设置即可。

class MyComponent extents Component {
    render() {
        //you can access it here if you want
        let myprop1 = window.Configs.prop1;
        return(){
            <div>myprop2 is: {window.Configs.prop2}</div>       
        }
    }
} 

步骤#4。利润?

不需要

或不需要涉及 webpack、webpack-externals、webpack-config、从 'config' 导入 Config 或任何其他 BS。

为什么它有效?因为我们声明"配置"是窗口对象的道具,并全局加载它。

就像Joseph Fehrman所说的那样,没有只考虑JSON,使用JS对我有用。这就是我所做的。

我创建了一个名为配置的JS文件.js其中包括我所需的配置

var configs = {
"aUrl": "https://localhost:9090/",
"bUrl": "https://localhost:9445/"};

然后在索引中.html我添加了它。

<body>
<div id='root'></div>
<script src="configurations.js"></script>
<script src="dist/bundle.js"></script></body>

然后在 webpack.config 中.js我像这样将其添加到外部。(请注意,在配置.js中,变量的名称是配置(。

externals: {
    config:  "configs", 
}

然后在我想要它的地方,我可以导入它并很好地使用它。这在部署后我能够更改配置的地方完美运行(也就是说,不必重新编译我的捆绑包.js保持不变的代码:-((。下面给出了一个显示如何使用它的示例。

import { Component } from 'react';
import axios from 'axios';
import Config from 'config';
/**
* @class GetProductAreas
* @extends {Component}
* @description Get ProductAreas
*/
class GetProductAreas extends Component {
    /**
    * @class GetProductAreas
    * @extends {Component}
    * @description get product areas
    */
    getproductAreas() {
        const url = Config.aUrl;
        return axios.get(url).then((response) => {
            return (response.data);
        }).catch((error) => {
            throw new Error(error);
        });
    }
}
export default (new GetProductAreas());

这个问题有点模糊。 我想我知道你在要求什么。 只要您打算使用 Webpack 或 Browserify,您就可以执行以下操作。 它确实需要稍微不同的思维,而不是使用 JS 文件来掩盖它的纯 JSON 文件。

配置.js:

let config = {
  option1: true,
  option2: false
}
module.exports = config;

然后,使用配置从您的文件中,您可以执行类似于以下内容的操作。

应用.js:

import React from 'react';
import ReactDOM from 'react-dom';
import config from './my/relative/config/path/config';
import MyOtherComponent from './components/my_component';
let component = (<MyOtherComponent config={config} />);
ReactDOM.render(component, document.querySelector('mount'));

最后一个解决方案效果很好,这里有一些改进:

配置文件,位于/public 文件夹中:

配置.js

var Configs = {
  var1: "value",
  var2: "value2"
}

在/public/index.html 文件中,在标头中添加脚本调用

<head>
....
<script src="config.js"></script>
....
</head>

最后,从代码调用 var。效果很好!

import React from 'react'
.... 
const data = window.Configs.var1

有了这个解决方案,我可以拥有多台服务器而无需重新编译,而且很容易做到。

相关内容

最新更新