React Native

react-native-config를 사용해서 env 설정하기 (+ ios 캐싱 문제 해결)

citron031 2022. 12. 20. 20:44

React Native에서 env 환경 변수를 편리하게 사용할 수 있도록 돕는 라이브러리로 react-native-config를 사용할 수 있다.

npm i react-native-config

설치 후 .env 파일을 생성한다.

// .env
BLOG_URL=https://www.tistory.com/

이제 실제 컴포넌트에서 Config를 불러와 환경 변수를 사용할 수 있다.

 

import React from 'react';
import {Text, View} from 'react-native';
import Config from 'react-native-config';

const App = () => {
	return (
    	<View>
        	<Text>tistory - {Config.BLOG_URL}</Text>
        </View>
    )
}

 

# ios 환경에서는 env 파일의 내용이 변경되지 않는 문제가 있다.

module 내부에서 캐싱이 되는 것 같은데, 값을 변경하고자 한다면 node_modules/react-native-config 폴더 삭제 후 다시 npm install react-native-config 하자.

 

🚁 안드로이드 환경에서 적용되지 않을 때 다음과 같이 +가 있는 줄을 추가한다.

  • android/settings.gradle

다음의 두 줄을 추가한다.

+ include ':react-native-config'
+ project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')

 

  • android/app/build.gradle
project를 추가한다.
dependencies {
	implementation "com.facebook.react:react-native:+"  // From node_modules
+	implementation project(':react-native-config')
}
  • android/app/src/main/java/com/프로젝트_이름/MainApplication.java

import와 new ReactNativeConfigPackage() 추가.

+ import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;

@Override
protected List<ReactPackage> getPackages() {
	   return Arrays.asList(
       		new MainReactPackage()
+      		new ReactNativeConfigPackage()
    );
}

 

https://www.npmjs.com/package/react-native-config

 

react-native-config

Expose config variables to React Native apps. Latest version: 1.4.11, last published: 3 months ago. Start using react-native-config in your project by running `npm i react-native-config`. There are 104 other projects in the npm registry using react-native-

www.npmjs.com