FrontEnd/React

[React] Vite 기반 프로젝트에서 동적 import로 이미지 불러오기

검정색필통 2023. 2. 11. 12:38

정적으로 이미지를 로드하는 방법은 다음과 같다.

import timeIcon from "@/assets/icons/time.png"
import placeIcon from "@/assets/icons/place.png"

하지만 필요한 이미지가 경우에 따라 달라질 때가 있다.

예를 들어 프로필 사진을 보여주어야 한다면 사람의 수는 100명, 1000명이 넘는데 이 모든 이미지를 정적으로 불러와 사용할 수는 없을 것이다.

 

Webpack으로 빌드하는 방식에서는 require을 사용해서 동적으로 이미지를 불러올 수 있지만

Vite와 같이 ESBuild로 할 경우 require이 import와 export로 대체되기 때문에 사용할 수 없다.

그러면 어떻게 동적으로 이미지를 불러올 수 있을까?

 

https://stackoverflow.com/questions/67995027/vite-react-dynamic-image-url

 

vite react dynamic image url

hello guys i have problem with vite react dynamic images url not loading correctly and thats my component <Flex> {data?.map((tag) => ( <Box key={tag._id}> <

stackoverflow.com

https://gogomalibu.tistory.com/188

 

[Vite&Typescript] Dynamic Image src

Vite와 Typescript로 구현된 프로젝트에서 로컬(프로젝트 폴더 안)에 저장된 이미지들을 불러와야하는 케이스가 있다. 이런 구조로 구현했는데 실제로 빌드된 스크립트를 이용해 이미지를 불러오려

gogomalibu.tistory.com

export function getImgUrl(url: string, name: string){
  return new URL(url+'/'+name+'.png', import.meta.url).href
}

다음과 같은 방법으로 function을 만들어 함수가 호출 될때마다 이미지를 로드하도록 하였다.

import.meta.url은 현재 페이지의 url이기 때문에 상대 경로를 사용하거나

import.meta.url대신 절대경로를 적으면 보다 편리하게 함수를 사용할 수 있다.

export function getImgUrl(url: string, name: string | number) {
  return new URL(url + '/' + name + '.png', 'https://localhost:3000/src/assets/').href
}