ProgramingTip

구성 파일을 저장하고 React를 사용하여 읽는 방법

bestdevel 2020. 10. 26. 08:25
반응형

구성 파일을 저장하고 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 프레임 워크와 반응을 통합하고 있기 때문에 이것이 정말 유용하다는 것을 알았습니다. 이렇게하면 모든 구성을 한곳에 보관할 수 있습니다.

  1. package.json의 종속성 섹션에서 가져옵니다.

"properties-reader": "0.0.16"

  1. 이 모듈을 상단의 webpack.config.js로 가져옵니다.

const PropertiesReader = require('properties-reader');

  1. 속성 파일 읽기

const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;

  1. 이 상수를 구성으로 가져 오기

externals: { 'Config': JSON.stringify(appProperties) }

  1. 수락 된 답변에 언급 된 것과 동일한 방식으로 사용하십시오.

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

참고 URL : https://stackoverflow.com/questions/30568796/how-to-store-configuration-file-and-read-it-using-react

반응형