Next.js에서 SVG 파일 불러오는 방법

곽태욱·2021년 10월 25일
4

https://github.com/teamsindy20/sobok/discussions/34

1. SVG 파일 그대로 불러오기

import Image from 'next/image'

<Image src="/images/home.svg" alt="home" width={24} height={21} />

2. Webpack

$ yarn add --dev @svgr/webpack

next.config.js

module.exports = {
  ...,
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    })
    return config
  },
}

A.tsx

import Icon from '../svgs/a.svg'

function A() {
  ...
  return (
    <Icon />
    ...
  )
}

3. React.js 컴포넌트로 변환하기

HomeIcon.tsx

import { SOBOK_ACHROMATIC_COLOR } from 'src/utils/constants'
import styled from 'styled-components'

const Svg = styled.svg`
  :hover {
    path,
    rect {
      stroke: #ff9f74;
    }
  }
`

const Path = styled.path`
  fill: #fff;
  stroke-linejoin: round;
  stroke-width: 1.4px;

  transition: stroke 0.5s ease;
`

const Rect = styled.rect`
  fill: #fff;
  stroke-linejoin: round;
  stroke-width: 1.3px;

  transition: stroke 0.5s ease;
`

type ColoredIconProps = {
  color?: string
}

function HomeIcon({ color = SOBOK_ACHROMATIC_COLOR }: ColoredIconProps) {
  return (
    <Svg width="100%" height="100%" viewBox="0 0 25.08 22.767">
      <g transform="translate(-29.313 -199.701)">
        <g data-name="444">
          <Path d="M41.853 200.351l-11.89 11.592h3.6v9.875h16.581v-9.875h3.6z" stroke={color} />
        </g>
        <Rect
          width={6.316}
          height={6.316}
          rx={0.843}
          transform="translate(38.695 212.287)"
          stroke={color}
        />
      </g>
    </Svg>
  )
}

export default HomeIcon
profile
이유와 방법을 알려주는 메모장 겸 블로그. 블로그 내용에 대한 토의나 질문은 언제나 환영합니다.

0개의 댓글