Frontend/Etc
Vite를 사용하면서 svg 컴포넌트로 만들기
이의찬
2024. 1. 1. 20:40
1. Why?
과제 테스트를 위해 React + Vite 환경에서 setting 진행중이다. svg파일을 React Component로 만들어 쓰려고 했지만 계속해서 정상적으로 랜더링이 이뤄지지 않았다.
결론부터 말하면 Vite 4.0 이후로 문법이 달라져서 생긴 이슈였다.
2. How?
순서
- vite-plugin-svgr 라이브러리 설치
- svg.d.ts 파일 생성(이름 달라도 상관 X)
- vite.config.ts 수정
- 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
SVG 파일, React Component로 가져오기 (Vite + TypeScript) (velog.io)