코딩/React Native

[RN] 환경변수 설정하기 .env 설정하기.

카슈밀 2025. 2. 6. 00:06
반응형

.env에 접근하는 방법은 process.env.REACT_APP_DOMAIN은 리액트의 경우였다.

 

RN의 경우 좀 까다롭다.

ios, android 둘다 설정해줘야하기때문에..

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

 

react-native-config

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

www.npmjs.com

 

설치방법

npm i react-native-config

npx pod-install

 

안드로이드에 대한 추가 단계

앱에 플러그인을 수동으로 적용해야 합니다 android/app/build.gradle.

// 2nd line, add a new apply:
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

 

 

android/app/build.gradle

defaultConfig {
    ...
    resValue "string", "build_config_package", "YOUR_PACKAGE_NAME_IN_ANDROIDMANIFEST_XML"
}


// 아래와 같이기입
/// resValue "string", "build_config_package", "com.프로젝트명"

 

 

프로젝트 내에서 호출하는 방법.

// .env
API_URL=https://myapi.com
GOOGLE_MAPS_API_KEY=abcdefgh


// anywhere.js
import Config from "react-native-config";

Config.API_URL; // 'https://myapi.com'
Config.GOOGLE_MAPS_API_KEY; // 'abcdefgh'

 

 

실제 배포시 env가 호출안되는 문제가 있을수도 있다.

Problems with Proguard

When Proguard is enabled (which it is by default for Android release builds), it can rename the BuildConfig Java class in the minification process and prevent React Native Config from referencing it. To avoid this, add an exception to android/app/proguard-rules.pro:

 

Proguard가 활성화되면(Android 릴리스 빌드의 경우 기본적으로 활성화됨) BuildConfig축소 프로세스에서 Java 클래스의 이름을 바꾸고 React Native Config가 참조하지 못하도록 할 수 있습니다. 이를 방지하려면 다음에 예외를 추가합니다 android/app/proguard-rules.pro.

-keep class com.프로젝트명.BuildConfig { *; }
 
728x90