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

IT技术 javascript reactjs jsx
2021-04-29 12:10:26

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

4个回答

接受的答案可能有效。然而,为什么要把它弄得这么复杂?

步骤1。创建一个文件 Config.js,有内容

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

第2步。通过脚本标签加载 index.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' 导入配置或任何其他 BS。

为什么有效?因为我们将 'Configs' 声明为 window 对象的一个​​ prop,并全局加载它。

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

我创建了一个名为configuration.js的JS 文件,其中包含我需要的配置

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

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

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

然后在webpack.config.js 中,我将它添加到这样的外部(请注意,在configuration.js 中,变量的名称是configs)。

externals: {
    config:  "configs", 
}

然后在任何我想要的地方,我可以导入它并很好地使用它。这非常有效,我可以在部署后更改配置(即不必重新编译我的 bundle.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 文件。

配置文件:

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 文件夹中的配置文件:

配置文件

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

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