티스토리 뷰

728x90
반응형

create-react-app.dev/docs/adding-custom-environment-variables/

 

Create React App · Set up a modern web app by running one command.

> Note: this feature is available with `react-scripts@0.2.3` and higher.

create-react-app.dev

 

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

 

이런 순서로 말이죠

 

으흠 그렇다면 qa, stage 와 같은 환경은 어떻게 .env를 구성하면 될까요

 

 

공식문서에는 딱히 이에대한 언급이 없으니 일단 스크립트를 뒤져보기로 합니다.

 

package.json 파일을 열어보면

 

npm run build, npm start는 모두 react-scripts 를 실행합니다

 

react-scripts 패키지를 살펴보니

 

scripts 폴더에 각 명령어에 해당하는 파일들이 있네요

 

 

파일을 살펴보니

require('../config/env');

 

이 부분이 env를 구성하는것으로 보입니다

 

config/env.js를 열어봅시다

 

 

 

dotenv 패키지를 이용해서 여러개의 env 파일들을 순차적으로 읽어서 로드하고 있습니다

 

그런데 주석을 보니 이렇게 적혀있네요

 

dotenv will never modify any environment variables that have already been set.

 

dotenv 공식문서에도 적혀있는 내용입니다.

 

그러니깐 dotenv는 이미 설정되어있는 환경변수는 절대로 변경하지 않는다고 하네요

 

그말인즉슨 config/env.js 가 .env파일을 읽기 전에 환경변수를 세팅하면 되겠네요

 

 

 

https://www.npmjs.com/package/dotenv-cli

 

dotenv-cli

A global executable to run applications with the ENV variables loaded by dotenv

www.npmjs.com

 

npm install dotenv-cli --save-dev

 

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

 

 

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

 

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

 

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

 

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

 

 

 

 

 

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함