React - SVGR 설치
React - SVGR 설치
1. Vite project에서 SVGR 설치
1
npm install -D vite-plugin-svgr
2. vite.config.ts 설정
1
2
3
4
5
6
7
8
9
10
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
export default defineConfig({
plugins: [
react(),
svgr(),
],
})
3. 타입 선언 추가 (TypeScript 사용 시)
1
/// <reference types="vite-plugin-svgr/client" />
4. 사용 방법
- Vite 방식
1
2
3
import Icon from '@/assets/icon.svg?react';
<Icon />
?react를 붙여야 하는 이유- Vite는 기본적으로 SVG를 URL으로 처리함
- 따라서 ?react를 붙여야 React Component로 변환됨
- CRA(Create React App) 방식
1
import { ReactComponent as Icon } from './icon.svg';
| 구분 | CRA | Vite |
|---|---|---|
| SVG React 변환 | 기본 내장 | 별도 plugin 필요 |
| import 방식 | { ReactComponent as Icon } |
?react |
| 설정 접근 | Webpack 숨김 | 설정 파일 명시적 |
This post is licensed under
CC BY 4.0
by the author.
