배포 환경에 따라 환경 변수(env) 셋팅하기

yes·2023년 3월 13일
0

.env 종류와 명령어에 따른 .env 우선순위

개발환경과 배포환경을 설정하는 방법으로는 환경변수 선언(.env)을 통해 한다.

env의 종류는 여러가지가 있다. .env.local, .env.development, .env.test, .env.production 이 있다.

Adding Custom Environment Variables | Create React App

What other .env files can be used?

Note: this feature is available with react-scripts@1.0.0 and higher.

.env: Default.

.env.local: Local overrides. This file is loaded for all environments except test.

.env.development, .env.test, .env.production: Environment-specific settings.

.env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

Files on the left have more priority than files on the right:

npm start: .env.development.local, .env.development, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm test: .env.test.local, .env.test, .env (note .env.local is missing)

These variables will act as the defaults if the machine does not explicitly set them.

react 기반의 프로젝트는 npm start, npm run build, npm run test 와 같은 명령어가 있습니다.

각 명령어는 위에서 언급한 우선순위에 의거해서 .env 파일을 읽습니다.

npm start는 .env.development.local > .env.development > .env.local > .env

npm run build는 .env.production.local > .env.production > .env.local > .env

특정 환경 변수의 우선순위를 강제로 높이기

1. dotenv-cli

npm install dotenv-cli --save-dev
yarn add dotenv-cli --save-dev

터미널에서 dotenv를 사용할수 있는 패키지를 설치합니다.

"scripts": {
	    "start": "react-scripts start",
	    "build": "react-scripts build",
	    "test": "react-scripts test --env=jsdom",
	    "eject": "react-scripts eject",
	    "build:development": "dotenv -e .env.development react-scripts build",
	    "build:qa": "dotenv -e .env.qa react-scripts build",
}

그리고 dotenv 명령어를 통해 특정 .env 파일을 먼저 읽도록 합시다

이렇게 하면 react-scripts build가 실행되어 env 파일을 우선순위에 따라 로드하기 전에

지정한 파일을 먼저 읽어서 환경변수를 설정했기때문에

이 변수들이 그대로 남아있게 됩니다

2. env-cmd

yarn add env-cmd --save-dev

start 스크립트의 환경 변수 우선 순위가 .env.development가 더 높은데, .env로 적용 하고 싶으면 아래와 같이 스크립트를 수정 합니다.

"start": "env-cmd -f .env react-scripts start"

로컬 개발과 배포 빌드 start 스크립트를 다르게 설정 하고 싶을 경우에는 스크립트 실행 이름을 아래와 같이 설정 할 수도 있습니다.

"start": "react-scripts start",
"start:prod": "env-cmd -f .env react-scripts start",

비고

.env.qa 이렇게 파일 만들어서 커스텀해서 환경변수를 적용할 수도 있다. (두 라이브러리 모두 가능)

env-cmd 사용 추천!! (첫번째 라이브러리는 .env 기본의 우선 수위는 높여주지 못하는 것으로 확인함)

Reference

react 프로젝트 local, dev, qa, production 환경을 구성해볼까요

[react] 실무 개발 환경/배포 환경 설정(.env)

[React] 배포 환경에 따라 환경 변수(env) 셋팅하기 - 기록하며 성장하기

0개의 댓글