Appearance
React Environment Variables with dotenv
CRA를 이용해 프로젝트 생성 시,
- dotenv 패키지 설치
shell
npm install dotenv
- 프로젝트 루트에 .env 파일 생성
- "REACTAPP" 으로 시작하는 변수 작성
- 변수를 사용하려는 곳에서 require('dotenv').config() 한 후, process.env.<변수명>으로 환경변수에 접근
CRA를 이용하지 않고 프로젝트 생성 시, ( 현재 출결버스 V2 )
✔ DefinePlugin
Webpack의 DefinePlugin을 사용해 process.env 라는 전역 변수 정의
javascript
// webpack.config.js
const webpack = require('webpack');
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env);
}),
]
}