-
[node.js] 환경 설정 파일 분리를 위한 dotenv, env-cmdWEB_DEV 2023. 7. 7. 09:11
* 개요
- 개발환경과 운영환경을 분리 하여 .env 파일을 정의 할 수 있다.
* 패키지 설치
npm install dotenv env-cmd --save
* 파일 정의 예시
개발환경 -> .env.development
PORT = "4000" NODE_ENV = "development" APP_URL = "http://localhost:4000" ORIGIN = "http://localhost:3000" JWT_SECRET = "super_secret"
운영환경 -> .env.production
PORT = "4000" NODE_ENV = "production" APP_URL = "http://localhost:4000" ORIGIN = "http://localhost:3000" JWT_SECRET = "super_secret"
* package.json 예시
- front-end
"scripts": { "dev": "next dev", "build:dev": "env-cmd -f .env.development next build", "build:production": "env-cmd -f .env.production next build", "start:dev": "env-cmd -f .env.development next start", "start:production": "env-cmd -f .env.production next start", "lint": "next lint" },
- back-end
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "env-cmd -f .env.development nodemon --exec ts-node ./src/server.ts", "start:production": "env-cmd -f .env.production ts-node src/index.ts", "typeorm": "typeorm-ts-node-commonjs" },
* source-code 에 사용 예시
import dotenv from 'dotenv'; # env 파일을 .env.dev .env.prd 로 분리 할 경우 아래와 같이 파일 명 지정 dotenv.config({ path: ".env.dev" }); const origin = process.env.ORIGIN;
* 참고자료
https://www.daleseo.com/js-dotenv/
dotenv로 환경 변수를 .env 파일로 관리하기
Engineering Blog by Dale Seo
www.daleseo.com