如何存储配置文件并使用 React 读取它 [英] How to store Configuration file and read it using React

查看:51
本文介绍了如何存储配置文件并使用 React 读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react.js 的新手我已经实现了一个组件,我在其中从服务器获取数据并使用它,

I am new on react.js I have implemented one component in which I am fetching the data from server and use it like,

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'
        //});
    });
},

我想将 Url 存储在配置文件中,所以当我在测试服务器或生产上部署它时,我只需要更改配置文件上的 url,而不是在 js 文件中,但我不知道如何在反应中使用配置文件.js

I want to store Url in configuration file so when I deployed this on Testing server or on Production I have to just change the url on config file not in js file but I don't know how to use configuration file in react.js

谁能指导我如何实现这一目标?

Can anyone please guide me how can I achieve this ?

推荐答案

使用 webpack,您可以将特定于 env 的配置放入 webpack.config.jsexternals 字段中

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

如果您想将配置存储在单独的 JSON 文件中,这也是可能的,您可以要求该文件并分配给 Config:

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

然后在你的模块中,你可以使用配置:

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

对于反应:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

不确定它是否涵盖您的用例,但对我们来说效果很好.

Not sure if it covers your use case but it's been working pretty well for us.

这篇关于如何存储配置文件并使用 React 读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆