Dha*_*tel 75 javascript configuration flux reactjs webpack
我是react.js的新手我实现了一个组件,我从服务器获取数据并使用它,如,
CallEnterprise:function(TenantId){
fetchData('http://xxx.xxx.xx.xx:8090/Enterprises?TenantId='+TenantId+' &format=json').then(function(enterprises)
{
EnterprisePerspectiveActions.getEnterprise(enterprises);
}).catch(function()
{
alert("There was some issue in API Call please contact Admin");
//ComponentAppDispatcher.handleViewAction({
// actionType: MetaItemConstants.RECEIVE_ERROR,
// error: 'There was a problem getting the enterprises'
//});
});
},
Run Code Online (Sandbox Code Playgroud)
我想将Url存储在配置文件中,所以当我在测试服务器或生产上部署它时,我只需更改配置文件中的url而不是js文件,但我不知道如何在react.js中使用配置文件
任何人都可以指导我如何实现这一目标?
Pet*_*ela 105
使用webpack,您可以将env特定的配置放入该externals字段中webpack.config.js
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
serverUrl: "https://myserver.com"
} : {
serverUrl: "http://localhost:8090"
})
}
Run Code Online (Sandbox Code Playgroud)
如果您想将配置存储在单独的JSON文件中,那也可以,您可以要求该文件并分配给Config:
externals: {
'Config': JSON.stringify(production ? require('./config.prod.json') : require('./config.dev.json'))
}
Run Code Online (Sandbox Code Playgroud)
然后在您的模块中,您可以使用配置:
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
Run Code Online (Sandbox Code Playgroud)
不确定它是否涵盖了您的使用案例,但它对我们来说效果很好.
ari*_*ris 47
如果您使用Create React App,则可以使用.env文件设置环境变量.文档在这里:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
基本上在项目根目录下的.env文件中执行类似的操作.
REACT_APP_SECRET_CODE=abcdef
Run Code Online (Sandbox Code Playgroud)
您可以使用组件从组件访问它
process.env.REACT_APP_SECRET_CODE
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93736 次 |
| 最近记录: |