Language/Javascript
React 환경 변수로 profile 지정하기
Seogineer
2025. 1. 3. 07:30
반응형
리액트도 Spring Boot의 application-dev.properties, application-prod.properties 처럼 각각 실행 환경에서 다른 설정을 사용하고 싶을 때 하는 설정 방법이 있다.
development 환경에서 http://localhost:8080을 production 환경에서 https://api.seogineer.com를 사용해서 동적으로 각 profile 마다 다른 URL을 사용하고 싶었다.
프로젝트의 root 경로에 .env.development, .env.production 파일을 생성하고 각 profile에 맞는 URL을 입력한다. 이때, 호출할 때 사용하는 이름은 접두사 REACT_APP_로 시작하여야 한다.
# .env.development
REACT_APP_API_URL=http://localhost:8080
# .env.production
REACT_APP_API_URL=https://api.seogineer.com
코드에서 아래와 같이 환경 변수를 사용할 수 있다.
import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL; // 환경 변수에서 API URL 가져오기
export const fetchData = async () => {
try {
const response = await axios.get(`${API_URL}/example`);
return response.data;
} catch (error) {
console.error('API 호출 오류:', error);
throw error;
}
};
어떤 profile을 사용할지는 실행 방법에 따라 나뉜다.
# development를 사용
npm start
# production을 사용
npm run build
.env.development, .env.production 외에도 아래와 같은 profile들을 사용할 수 있다.
- .env.test
- .env.local
- .env
- .env.development.local
- .env.test.local
- .env.production.local
실행할 때 profile에 따라 우선 순위가 달라진다.
.env.환경.local > .env.환경 > .env
참고
반응형