How to have a external JSON config file in react jsx(如何在React JSX中拥有外部JSON配置文件)
问题描述
我希望在基于Reaction的项目中有一个外部配置文件(JSON)。这就是最终结果,或者当我交付它(公共文件夹和bundle.js)时,也应该给出我的配置文件。用户应该能够根据他或她的意愿更改配置,并使用我的应用程序。也就是说,无需重新编译我的代码,用户就应该能够使用它。换句话说,配置文件不应与我的应用捆绑在一起。
JSON
LikeJoseph Fehrman说,不用只考虑推荐答案,使用JS对我很有效。这就是我所做的。
我创建了一个名为Configurations.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中,我将其添加到外部中,如下所示。(请注意,在configations.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());
这篇关于如何在React JSX中拥有外部JSON配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在React JSX中拥有外部JSON配置文件
基础教程推荐
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
