끄적이는 개발노트
React Native - .env 환경변수 본문
728x90
개발을 하다보면 외부에 공개되면 안되는 키나 중요 정보들처럼 보안이 필요한 값들이 있다. 이런 값들을 숨기고 유지보수를 쉽게 하기 위해 .env 파일에 환경변수로 만들어 사용하게 된다.
react native에서는 이를 위해 react-native-dotenv 라이브러리 활용이 필요하다.
https://www.npmjs.com/package/react-native-dotenv
react-native-dotenv
Load environment variables using import statements.. Latest version: 3.4.11, last published: a year ago. Start using react-native-dotenv in your project by running `npm i react-native-dotenv`. There are 93 other projects in the npm registry using react-nat
www.npmjs.com
1. 설치
npm install -D react-native-dotenv @types/react-native-dotenv
#or
yarn add -D react-native-dotenv @types/react-native-dotenv
2. babel.config.js
기본
// babel.config.js
module.exports = {
plugins: [
['module:react-native-dotenv']
]
};
옵션 추가
// babel.config.js
module.exports = {
plugins: [
[
'module:react-native-dotenv',
{
moduleName: '@env',
path: '.env',
blocklist: null,
allowlist: null,
safe: false,
allowUndefined: true,
verbose: false,
},
]
]
};
3. Typescript
types 폴더를 생성하고 env.d.ts 파일을 만들어준다.
// env.d.ts
declare module '@env' {
export const WebClientId: string;
}
tsconfig.js 파일에 typeRoots를 본인 types 폴더 경로에 맞게 추가한다.
// tsconfig.json
{
...
"compilerOptions": {
...
"typeRoots": ["./src/types", "./node_modules/@types"]
...
}
...
}
4. 코드
저번에 구현한 구글 로그인의 WebClientId를 환경변수로 만들어 사용해보았다.
// .env
WebClientId=값
// home.tsx
...
import {WebClientId} from '@env';
...
...
useEffect(() => {
GoogleSignin.configure({
webClientId: WebClientId,
});
}, []);
...
728x90
'React Native' 카테고리의 다른 글
React Native - Release Keystore 생성 (0) | 2025.02.04 |
---|---|
React Native - 구글 로그인 (3) 로그인 상태 확인 onAuthStateChanged (0) | 2025.02.01 |
React Native - 구글 로그인 (2) @react-native-google-signin/google-signin (0) | 2025.02.01 |
React Native - 구글 로그인 (1) Firebase 연동 (0) | 2025.02.01 |
React Native - Storage 저장(AsyncStorage / KeyChain) (0) | 2025.01.26 |