환경변수 .env
파일의 load 방식의 차이를 React, Node 에서 알아본다.
PORT=4000
REACT_APP_API_KEY=~~~~
REACT_APP_API_URL=~~~~
react 에서는 두가지 사항을 지키고 써야한다.
- react 에서는 환경변수 접두사
REACT_APP_
을 붙여야한다.
(이는 시스템 환경변수와 REACT 앱 내에서의 변수에 차이를 두기 위함이다.)- 반드시
process.env.
를 통해 환경변수에 접근해야한다.
.env 파일이 인식이 안됨.
import dotenv from 'dotenv';
const env = dotenv.config({path: '../.env', encoding: 'utf8'}).parsed;
const {REACT_APP_API_URL, REACT_APP_API_KEY} = env;
// undefined error
import dotenv from 'dotenv';
const env = dotenv.config({path: '../.env', encoding: 'utf8'});
console.log(env);
다음과 같은 에러를 뿜는다.
{
error: TypeError: fs.readFileSync is not a function
at Object.config (http://localhost:(중략)js/…
}
node에서와 달리 dotenv.config 가 파일 읽기 그 자체로 인식되고있다.
원래 .config 메소드의 output 원형은 다음과 같다.
export interface DotenvConfigOutput {
error?: Error;
parsed?: DotenvParseOutput;
}
도무지 왜 이런 현상이 일어나는지 모르겠다.
React 팀에서 애초에 일반 노드와 다르게 동작하도록 설계한거같다.
process.env.
로 접근하는 것은 가능import dotenv from 'dotenv';
dotenv.config({path: '../.env', encoding: 'utf8'});
const {REACT_APP_API_URL, REACT_APP_API_KEY} = process.env;
당연히 REACT_APP
같은 접두사도 필요 없고
destructuring 도 가능하다.
.env
파일만 파싱하기도 쌉가능import dotenv from 'dotenv';
const envSet = dotenv.config({path:'../../.env', encoding: 'utf8'}).parsed;
// 정상 출력
console.dir(envSet);