Vite에서 SVG 사용하는 두 가지 방법 (React + TypeScript 기준)

Vite에서 SVG 사용하는 두 가지 방법 (React + TypeScript 기준)
TILPosted On Apr 18, 20252 min read

✅ 1. React 컴포넌트로 사용하는 방법 (?react 쿼리)

SVG를 직접 React 컴포넌트로 import 하여 사용하려면 vite-plugin-svgr 플러그인이 필요합니다.


📦 1-1. 설치

npm install vite-plugin-svgr --save-dev
# 또는
yarn add vite-plugin-svgr --dev

⚙️ 1-2. vite.config.ts 설정

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

export default defineConfig({
  plugins: [react(), svgr()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
});

🧩 1-3. TypeScript 선언 추가 (svg.d.ts)

// src/svg.d.ts
declare module "*.svg?react" {
  import * as React from "react";
  export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  export default ReactComponent;
}

🧪 1-4. 사용 예시

// 예: src/components/Icon.tsx
import { ReactComponent as HeartIcon } from "@/assets/icons/heart.svg?react";

const Icon = () => {
  return <HeartIcon width={32} height={32} fill="red" />;
};

export default Icon;

📁 2. 이미지 파일처럼 사용하는 방법 (img 태그)

vite-plugin-svgr 없이도 기본적으로 SVG 파일은 URL로 import해서 이미지처럼 사용할 수 있습니다.


📂 2-1. import 방식

// 예: src/components/ImageIcon.tsx
import heartUrl from "@/assets/icons/heart.svg";

const ImageIcon = () => {
  return <img src={heartUrl} alt="Heart" width={32} />;
};

export default ImageIcon;

🧩 2-2. TypeScript 선언 추가 (svg.d.ts)

// src/svg.d.ts
declare module "*.svg" {
  const src: string;
  export default src;
}

⚠️ *.svg?react*.svg 둘 다 선언해주면 두 방식 모두 사용할 수 있습니다.


🔁 3. 마무리 - 개발 서버 재시작

npm run dev
# 또는
yarn dev