환경변수 PUBLIC_URL 정적 리소스/절대 경로 가져오기

김민아·2023년 1월 17일
1
post-thumbnail

정적 리소스의 올바른 경로 가져오기

📌 문제 발단

로컬환경(:3000)으로 테스트 하다가 github에 호스팅을 하면서 루트 경로가 아닌 /weather/ 등 path를 추가하였다. 그런데, public에 있는 api 아이콘 경로가 깨지는 현상이 있었다.

// 코드 일부 
const CurrentWeather = ({data}) => {
  return (
    <div className="weather">
      <div className="top">
        <div>
          <p className="city">{data.city}</p>
          <p className="weather-description">{data.weather[0].description}</p>
        </div>
*        <img alt="weather" className="weather-icon" src={`/icons/${data.weather[0].icon}.png`} />
      </div>
    </div>
  )
}

위 코드는 api data에서 받은 파일명으로 /icons 절대 경로를 생성하는 코드 일부이다. 앱을 빌드할 때 번들러는 public 폴더의 정적 리소스를 참조하는 스크립트를 생성하는데, 하위 도메인을 루트로 설정하지 않는 것 같았다.

✅ 환경변수 PUBLIC_URL

When you run npm run build, Create React App will substitute %PUBLIC_URL% with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL.

In JavaScript code, you can use process.env.PUBLIC_URL for similar purposes: ...
using-the-public-folder | create-react-app.dev

역시 공식 문서에는 답이 있다 🥹
process.env.PUBLIC_URL은 CRA가 빌드 때 올바른 절대 경로를 PUBLIC_URL로 대체되어 클라이언트-사이드 라우팅이나 루트가 아닌 URL에 호스트하더라도 유연하게 프로젝트가 작동할 수 있도록 돕는다는 것이다. ✨

그럼 코드의 경로를 수정하지 않고도 쉽게 하위 디렉토리나 도메인에 쉽게 이동할 수 있다.

이미 우리에게 익숙했던.. 거였네?

%PUBLIC_URL% 어디에서 많이 봤나 했더니 CRA를 했을 때 생성되는 index.html에서 파비콘, 로고, 매니페스트 등을 import할 때 있었다. 🥹

html에서는 → %PUBLIC_URL%

<link rel="stylesheet" href="%PUBLIC_URL%/css/main.css">
<img src="%PUBLIC_URL%/images/logo.png" alt="Logo">

javascript → process.env.PUBLIC_URL

// 코드 일부 
const CurrentWeather = ({data}) => {
  return (
    <div className="weather">
      <div className="top">
        <div>
          <p className="city">{data.city}</p>
          <p className="weather-description">{data.weather[0].description}</p>
        </div>
*        <img alt="weather" className="weather-icon" src={`${process.env.PUBLIC_URL}/icons/${data.weather[0].icon}.png`} />
      </div>
    </div>
  )
}

위에 코드를 PUBLIC_URL로 변경해 주었다. 해결!

출처

0개의 댓글