본문 바로가기
Frontend/Etc

Vite를 사용하면서 svg 컴포넌트로 만들기

by 이의찬 2024. 1. 1.

1. Why?

과제 테스트를 위해 React + Vite 환경에서 setting 진행중이다. svg파일을 React Component로 만들어 쓰려고 했지만 계속해서 정상적으로 랜더링이 이뤄지지 않았다. 

 

결론부터 말하면 Vite 4.0 이후로 문법이 달라져서 생긴 이슈였다. 


2. How?

순서

  1. vite-plugin-svgr 라이브러리 설치
  2. svg.d.ts 파일 생성(이름 달라도 상관 X)
  3. vite.config.ts 수정
  4. tsconfig.json 수정

svg.d.ts

declare module '*.svg' {
  const content: React.FC<React.SVGProps<SVGElement>>;
  export default content;
}

 

vite.config.ts

import svgr from 'vite-plugin-svgr';

export default defineConfig({
  plugins: [react(), svgr()],

tsconfig.json 

{
    "types": ["vite-plugin-svgr/client"],
    "include": ["svg.d.ts"],
 }

작성방법

import { ReactComponent as Logo } from '@public/assets/image/logo.svg';

return <Logo />

원래는 위와 같이 { ReactComponent as ~ } 형태로 svg를 컴포넌트화 해서 사용했었다.

import Logo from '@public/assets/image/logo.svg?react';

return <Logo />

하지만 Vite 4.0 이후로 문법이 달라지면서 위와 같은 방식으로 코드를 작성해야 svg를 컴포넌트화 할 수 있다. 변경되었다는 글을 찾기 힘들어서 꽤나 고생했는데, 다른 사람은 쉽게 사용하길 바란다.


3. 레퍼런스

reactjs - Unable to import SVG with Vite as ReactComponent - Stack Overflow

 

Unable to import SVG with Vite as ReactComponent

Tried to use this library: vite-plugin-react-svg and had no success by importing it like: import { ExternalLink } from 'assets/svg/link-external.svg?component'; Are there any workarounds for this ...

stackoverflow.com

SVG 파일, React Component로 가져오기 (Vite + TypeScript) (velog.io)

 

SVG 파일, React Component로 가져오기 (Vite + TypeScript)

SVG 파일 React Component 가져오기

velog.io