yarn add react-native-dotenv
// typescript의 경우
yarn add @types/react-native-dotenv -D
React Native는 CocoaPods를 사용하여 iOS 프로젝트 종속성을 관리
대부분의 React Native 라이브러리는 이와 동일한 규칙을 따름.
사용 중인 라이브러리가 그렇지 않은 경우 README에서 추가 지침을 참조.
기본 iOS 프로젝트에 연결하기 위해 iOS 디렉토리에서 pod install 실행.
// 1. package.json이 존재하는 root 경로에서
cd ios
pod install
이 작업이 완료되면 앱 바이너리를 다시 빌드하여 새 라이브러리 사용을 시작한다.
yarn ios
module.exports = {
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
["module:react-native-dotenv", {
"moduleName": "@env", // import 해올 때 react-native-env -> @env 가능.
"path": ".env",
"blacklist": null, // 허용 목록 및 차단 목록을 지정 가능. env 변수 범위 제한
"whitelist": null,
"safe": true, // .env 파일에 정의된 환경 변수만 허용
"allowUndefined": true // 정의되지 않은 변수 가져오기를 허용 -> 값이 정의되지 않음
}]
]
};
const babel = code => code
declare module '@env' {
export const API_URL: string;
export const API_TOKEN: string;
// ... export const 환경변수 이름: string;
}
{
...
"compilerOptions": {
...
"typeRoots": ["./src/types"], // (1) 에서 생성한 types 폴더
...
}
...
}
import {API_URL, API_TOKEN} from "@env"
// 또는
// import {API_URL, API_TOKEN} from "react-native-dotenv"
fetch(`${API_URL}/users`, {
headers: {
'Authorization': `Bearer ${API_TOKEN}`
}
});
velog.io/@devstefancho/
jeonghwan-kim.github.io
rn auto linking