My Boundary As Much As I Experienced

VITE에서 SVGR 라이브러리를 사용할 때 쓰는 신 문법 (ReactComponent를 찾을 수 없다는 에러 해결) 본문

FrontEnd/React

VITE에서 SVGR 라이브러리를 사용할 때 쓰는 신 문법 (ReactComponent를 찾을 수 없다는 에러 해결)

Bumang 2024. 5. 16. 22:52

ReactComponent를 찾을 수 없다는 에러 해결법

예전 사이드 프로젝트 진행 도중 UX디자이너 분이 네비게이션 바를 바꾸셨다.

react-icons에 있는 기성 아이콘이 아닌 커스텀 svg아이콘을 쓰게 되어 svgr을 쓰게 됐다.

그런데 아래 에러가 뜨는 것이다. 

Module '"*.svg"' has no exported member 'ReactComponent'.
Did you mean to use 'import ReactComponent from "*.svg"' instead?

 

 

챗지피티에게 물어본 결과, 헛소리밖에 듣지 못했다.

아무래도 SVGR의 최신버전을 쓰면서 뭔가 다른 문법으로 바뀐 것으로 의심되었다.

찾아보니 SVGR을 4버전 이상으로 이용할 때 svg를 import하는 방식이 달라졌다.

 

아래는 새로운 설정 방식이다.

 

 

1. vite-plugin-svgr 설치

npm install vite-plugin-svgr --save-dev

2. vite.config.ts 수정

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import svgr from 'vite-plugin-svgr';

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

 

 

 

3. 컴포넌트 파일에서 사용

이전 버전에서는 SVG를 ReactComponent로서 import하고, as 별칭으로 변수명을 지정해주었다.

// 옛날 문법
import { ReactComponent as RandomSVG } from 'assets/images/test.svg';

const Component = () => {
  return (<RandomSVG />)
}

 

4.0.0 이상 버전에서는 사용 방법이 살짝 다르다.

SVG 파일을 가져올 때, ?react라는 쿼리를 붙여 앨리어싱을 건너뛰어 기본 내보내기를 사용할 수 있다.

import RandomSVG from 'assets/images/test.svg?react';

const Component = () => {
  return (<RandomSVG />)
}

 

 

이렇게 사용할 경우 svg.d.ts 파일을 생성해야 한다. 나는 루트단에 놓았다. (다른 곳에 놓아도 상관은 없나?)

 

declare module "*.svg" {
  const value: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
  export default value;
}

 

 

이래서 챗지피티가 아무리 좋아졌어도, 쎄하면 바로 공식문서와 스택오버플로우를 뒤져봐야된다.

 

 

참고자료:

https://velog.io/@yoonth95/SVG-%ED%8C%8C%EC%9D%BC-React-Component%EB%A1%9C-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0-Vite-TypeScript

 

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

SVG 파일 React Component 가져오기

velog.io

 

https://velog.io/@yeguu037/ReactTS-SVG-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0