React + Vite에서 SVG component 만들기 (with. Styled Components)

LEEJAEJUN·2023년 11월 22일

SVG component 만들어 쓰기

https://stackoverflow.com/questions/70309561/unable-to-import-svg-with-vite-as-reactcomponent

위 글에서 보다시피 처음에는 vite-plugin-svgr 이라는 플러그인을 사용해서 컴포넌트로 만들려고 했다. 하지만 아래와 같은 에러가 발생했다.

paymentStyle.ts:3 Uncaught SyntaxError: The requested module '/src/assets/kakaoPay.svg?import' does not provide an export named 'ReactComponent' (at paymentStyle.ts:3:10)

아래에 npm install @svgr/rollup -D 을 사용해야 한다는 댓글을 보고, Vite는 빌드할 때 Rollup을 쓴다는 것을 어디서 본 것 같기도 해서 이걸로 설치해서 써봤더니 해결!

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from '@svgr/rollup';

export default defineConfig({
  plugins: [react(), svgr()]
});
// svg.d.ts
declare module '*.svg' {
  import React from 'react';
  const src: string;
  export const ReactComponent: React.FunctionComponent<
    React.SVGProps<SVGSVGElement>
  >;
  export default src;
}
// tsconfig.json
"include": ["src", "custom.d.ts", "svg.d.ts"],

위 처럼 파일을 세팅하고 나니 styled component 형태로 만들 수 있었다.

// styles.ts
import { ReactComponent as kakaoPaymentLogo } from '../../assets/kakaoPay.svg';

export const KakaoPayLogo = styled(kakaoPaymentLogo)`
  width: 33px;
  height: 33px;
  object-fit: cover;
`;
profile
always be fresh

0개의 댓글