[dotenv] react-typesciprt-dotenv

DONNIE·2023년 10월 25일
0

Typescript

목록 보기
2/2

react-typescript 환경에서 env 환경변수 사용하기

  1. dotenv 설치
npm install dotenv
  1. .env file 생성
  • 루트폴더에 .env 파일 생성
  • ''나 띄어쓰기없이 작성
REACT_APP_YOUR_KEY_NAME=YOUR_SECRET_KEY
REACT_APP_YOUR_URL=YOUR_SITE_URL
  1. *.d.ts 파일 생성
  • 타입을 명시해야한다 ^ -^;;
/// <reference types="react-scripts" />

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      REACT_APP_YOUR_KEY_NAME: string | undefined;
      REACT_APP_YOUR_URL: string | undefined;
    }
  }
}
  1. tsconfig.json 에 위의 타입명시 파일 include
.
.
.
"include" : [
	"env.d.ts"
]
  1. 컴포넌트에서 호출
  • 자바스크립트 프로젝트와 다르게 변수로 선언해야 한다 . 아마도 || undefined 때문인듯
const YOUR_KEY = process.env.REACT_APP_YOUR_KEY_NAME || '';
profile
후론트엔드 개발자

0개의 댓글