react-native .env 설정

그니·2023년 8월 18일
0
post-thumbnail

라이브러리

react-native-dotenv

react-native-dotenv 설치


yarn add react-native-dotenv
// typescript의 경우 
yarn add @types/react-native-dotenv -D

iOS에서 네이티브 코드 연결


  • rn 공식홈페이지

  • React Native는 CocoaPods를 사용하여 iOS 프로젝트 종속성을 관리

  • 대부분의 React Native 라이브러리는 이와 동일한 규칙을 따름.

  • 사용 중인 라이브러리가 그렇지 않은 경우 README에서 추가 지침을 참조.

  • 기본 iOS 프로젝트에 연결하기 위해 iOS 디렉토리에서 pod install 실행.

// 1. package.json이 존재하는 root 경로에서
cd ios
pod install

이 작업이 완료되면 앱 바이너리를 다시 빌드하여 새 라이브러리 사용을 시작한다.

yarn ios

babel 세팅


  • root 경로의 'babel.config.js' 파일 수정
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 // 정의되지 않은 변수 가져오기를 허용 -> 값이 정의되지 않음
    }]
  ]
};

babel plugin

  • 기본적으로 바벨은 코드를 받아서 코드를 반환한다.
const babel = code => code
  • 바벨은 '파싱'과 '출력'만 담당하고 '변환' 작업은 다른 요소가 처리하는데 이것을 '플러그인'이라 부른다.

Typescript 설정


1. 라이브러리가 Typescript와 함께 작동하려면 모듈의 유형을 수동으로 지정.

  1. 'types' 폴더 생성
  2. 'types' 폴더 안에 '*.d.ts' or 'env.d.ts' 파일 생성
  3. 해당 파일에 모듈 유형 선언
declare module '@env' {
	export const API_URL: string;
  	export const API_TOKEN: string;
  	// ... export const 환경변수 이름: string;
}

2. tsconfig.json 수정

{
...
  "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

0개의 댓글