React에서 SVG를 표시하는 방법은 여러가지가 있다.
import Pohang from '@/assets/images/pohang.svg?react';
export const Component = () => {
return (
<img src={Pohang} />
)
}
export const Logo = ({width, height}) => {
// width , height 초기화 로직
return (
<svg width={wrapperWidth} heigt={wrapperHeight} viewBox={}>
<rect>
...
</rect>
</svg>
)
}
import Logo from './Logo.svg';
export const Header = () => {
return (
<Logo width={80} height={80} />
)
}
svgr이라는 svg파일을 리액트 컴포넌트로 변환시켜주는 라이브러리를 사용한다.
프로젝트에서 사용하는 번들러에 따라 설정방법이 달라진다.
vite-plugin-svgr을 별도로 사용vite의 기준으로 설명하자면
# npm
npm install --save-dev vite-plugin-svgr
# yarn
yarn add -D vite-plugin-svgr
# pnpm
pnpm add -D vite-plugin-svgr
import svgr from 'vite-plugin-svgr';
export default defineConfig({
plugins: [
...
svgr({
// React 컴포넌트를 디폴트로 export한다면 true (default: true)
exportAsDefault: true,
// 어떤 파일들이 SVGR 플러그인에 의해 처리될지를 지정
include: '**/*.svg?react',
}),
],
});
이 외에도 Export, esbuild 등 다양한 옵션을 지원한다.
// Set it to `true` to export React component as default.
// Notice that it will override the default behavior of Vite.
exportAsDefault: false,
// svgr options: https://react-svgr.com/docs/options/
svgrOptions: {
// ...
},
// esbuild options, to transform jsx to js
esbuildOptions: {
// ...
},
// A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should include. By default all svg files will be included.
include: '**/*.svg',
// A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.
exclude: '',
include:
어떤 파일들이 SVGR 플러그인에 의해 처리될지를 지정한다.
현재 '*/.svg?react'로 설정했기 때문에, 필요로하는 곳에서 import 시 경로에 .svg?react를 붙여야 svgr로 처리가 된다.
예시
이 설정을 통해 특정 SVG 파일들만 React 컴포넌트로 변환하고, 나머지 SVG 파일들은 일반적인 이미지 파일로 사용한다.
├── src
│ ├── assets
│ │ ├── logo.svg
│ └── ...
└── package.json
import Logo from '@/assets/images/logo.svg?react';
export const Header = () => {
return (
<Logo width={80} height={80} />
)
}