Javascript 如何存储配置文件并使用 React 读取它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30568796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store Configuration file and read it using React
提问by Dhaval Patel
I am new on react.js I have implemented one component in which I am fetching the data from server and use it like,
我是 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'
//});
});
},
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
我想将 Url 存储在配置文件中,所以当我在测试服务器或生产上部署它时,我只需要更改配置文件中的 url,而不是在 js 文件中,但我不知道如何在 react.js 中使用配置文件
Can anyone please guide me how can I achieve this ?
谁能指导我如何实现这一目标?
回答by Petr Bela
With webpack you can put env-specific config into the externalsfield in webpack.config.js
随着的WebPack你可以把ENV-特定的配置进入externals领域webpack.config.js
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
serverUrl: "https://myserver.com"
} : {
serverUrl: "http://localhost:8090"
})
}
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:
如果您想将配置存储在单独的 JSON 文件中,这也是可能的,您可以要求该文件并分配给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/...')
For React:
对于反应:
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.
不确定它是否涵盖您的用例,但它对我们来说效果很好。
回答by aris
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
如果您使用 Create React App,您可以使用 .env 文件设置环境变量。文档在这里:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
基本上在项目根目录的 .env 文件中做这样的事情。
REACT_APP_NOT_SECRET_CODE=abcdef
You can access it from your component with
您可以从您的组件访问它
process.env.REACT_APP_NOT_SECRET_CODE
回答by Joshua Underwood
You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
无论您使用什么设置,都可以使用 dotenv 包。它允许您在项目根目录中创建一个 .env 并像这样指定您的密钥
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
在您的应用程序入口文件中,您只需调用 dotenv(); 在像这样访问密钥之前
process.env.REACT_APP_SERVER_PORT
回答by Fangming
In case you have a .properties file or a .ini file
如果您有 .properties 文件或 .ini 文件
Actually in case if you have any file that has key value pairs like this:
实际上,如果您有任何具有这样的键值对的文件:
someKey=someValue
someOtherKey=someOtherValue
You can import that into webpack by a npm module called properties-reader
您可以通过名为properties-reader的 npm 模块将其导入 webpack
I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.
我发现这真的很有帮助,因为我正在将 react 与 Java Spring 框架集成,其中已经有一个 application.properties 文件。这有助于我将所有配置放在一个地方。
- Import that from dependencies section in package.json
- 从 package.json 中的依赖项部分导入
"properties-reader": "0.0.16"
"properties-reader": "0.0.16"
- Import this module into webpack.config.js on top
- 将此模块导入到 webpack.config.js 之上
const PropertiesReader = require('properties-reader');
const PropertiesReader = require('properties-reader');
- Read the properties file
- 读取属性文件
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
- Import this constant as config
- 将此常量作为配置导入
externals: {
'Config': JSON.stringify(appProperties)
}
externals: {
'Config': JSON.stringify(appProperties)
}
- Use it as the same way as mentioned in the accepted answer
- 按照已接受的答案中提到的相同方式使用它
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

