구성 파일을 저장하고 React를 사용하여 읽는 방법
나는 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'
//});
});
},
구성 파일에 Url을 저장하고 배포 할 때 js 파일이 아닌 구성 파일의 URL을 변경해야하지만 react.js에서 파일을 변경해야합니다.
누구든지 어디서 어떻게 얻을 수 있습니까?
webpack을 사용하면 특정 구성을 externals
필드에 넣을 수 있습니다 .webpack.config.js
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
serverUrl: "https://myserver.com"
} : {
serverUrl: "http://localhost:8090"
})
}
구성을 별도의 JSON 파일에 저장하려는 경우에도 가능합니다. 해당 파일을 요구하고 다음에 할당 할 수 있습니다 Config
.
externals: {
'Config': JSON.stringify(production ? require('./config.prod.json') : require('./config.dev.json'))
}
그런 다음 모듈에서 구성을 사용할 수 있습니다.
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
그것이 당신의 사용 사례를 확실하지 않지만 우리는 잘 작동하고 있습니다.
React App을 사용하여 환경 변수를 사용할 수 있습니다. 문서는 다음과 가능합니다.
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
기본적으로 프로젝트 루트의 .env 파일에서 이와 같은 작업을 수행하십시오.
REACT_APP_SECRET_CODE=abcdef
구성 요소에서 액세스 할 수 있습니다.
process.env.REACT_APP_SECRET_CODE
사용하는 설정에 관계없이 dotenv 패키지를 사용할 수 있습니다. 프로젝트 루트에 .env를 만들고 다음과 같이 키를 수 있습니다.
SERVER_PORT=8000
응용 프로그램 항목 파일에서 dotenv (); 이렇게 키에 액세스하기 전에
process.env.SERVER_PORT
.properties 파일 또는 .ini 파일이있는 경우
실제로 다음과 같은 키 값 쌍이있는 파일이있는 경우 :
someKey=someValue
someOtherKey=someOtherValue
properties-reader 라는 npm 모듈로 webpack으로 수 있습니다.
이미 application.properties 파일이있는 Java Spring 프레임 워크와 반응을 통합하고 있기 때문에 이것이 정말 유용하다는 것을 알았습니다. 이렇게하면 모든 구성을 한곳에 보관할 수 있습니다.
- package.json의 종속성 섹션에서 가져옵니다.
"properties-reader": "0.0.16"
- 이 모듈을 상단의 webpack.config.js로 가져옵니다.
const PropertiesReader = require('properties-reader');
- 속성 파일 읽기
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
- 이 상수를 구성으로 가져 오기
externals: { 'Config': JSON.stringify(appProperties) }
- 수락 된 답변에 언급 된 것과 동일한 방식으로 사용하십시오.
var Config = require('Config') fetchData(Config.serverUrl + '/Enterprises/...')
참고 URL : https://stackoverflow.com/questions/30568796/how-to-store-configuration-file-and-read-it-using-react
'ProgramingTip' 카테고리의 다른 글
SciPy를 사용 분위수-분위수 전부 (0) | 2020.10.26 |
---|---|
osx 10.10 HTTPS URL에 대한 Curl POST에서 SSLRead () 오류 발생 (0) | 2020.10.26 |
Docker 컨테이너의 실행 명령을 표시하는 방법 (0) | 2020.10.26 |
AWS CLI에서 와일드 카드를 사용하여 파일 그룹을`cp` 지불해야 할 일이 있습니까? (0) | 2020.10.26 |
DispatchQueue.main.async와 DispatchQueue.main.sync의 차이점 (0) | 2020.10.26 |