JEJ*_*EJC 7 javascript jsx reactjs
我想在基于React的项目中有一个外部配置文件(JSON)。那是最终的结果,或者当我交付它(公共文件夹和bundle.js)时,也应提供我的配置文件。用户应该能够根据自己的意愿更改配置并使用我的应用程序。在那里无需重新编译我的代码就可以使用它。换句话说,配置文件不应与我的应用捆绑在一起。
joe*_*not 13
接受的答案可能有效。然而,为什么要搞得这么复杂?
第1步。创建一个文件 Config.js,有内容
var Configs = {
prop1 = "abc",
prop2 = "123"
}
Run Code Online (Sandbox Code Playgroud)
第2步。通过脚本标签加载 index.html 中的文件。
<div id='root'></div>
<script src="Config.js"></script>
<script src="dist/bundle.js"></script></body>
Run Code Online (Sandbox Code Playgroud)
步骤#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>
}
}
}
Run Code Online (Sandbox Code Playgroud)
第四步。利润?
不需要或不需要涉及 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/"};
Run Code Online (Sandbox Code Playgroud)
然后在index.html 中我添加了它。
<body>
<div id='root'></div>
<script src="configurations.js"></script>
<script src="dist/bundle.js"></script></body>
Run Code Online (Sandbox Code Playgroud)
然后在webpack.config.js 中,我将它添加到这样的外部。(请注意,在configuration.js 中,变量的名称是configs)。
externals: {
config: "configs",
}
Run Code Online (Sandbox Code Playgroud)
然后在任何我想要的地方,我可以导入它并很好地使用它。这在我能够在部署后更改配置的地方非常有效(即不必重新编译我的 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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4899 次 |
| 最近记录: |