[Next.js] 에서 SVG 파일 사용하는 법 (feat. svgr 웹팩 설정하기, Image tag 사용하기)

LIMHALIM·2023년 11월 23일
3

1. svgr 라이브러리 사용하기

Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of Header.

svg 파일을 import하여 불러오기만 하면 자꾸 이 에러가 떠서.. 찾아보다가 svgr 라이브러리를 설치해서 웹팩을 설정해주니 아주 잘 불러와지더랍니다?
(이전 nextjs 프로젝트에서는 잘만 불러왔는데 갑자기 왜그러시는지...)


여튼 svgr 라이브러리를 사용해보자,,~!

svgr이란 svg 이미지를 react나 nextjs에서 쉽게 다루기 위해서 만들어진 webpack 설정이자 babel 설정이라고 합니다. 이를 이용하면 svg 파일을 컴포넌트화 하여서 사용할 수 있습니다!

  1. 라이브러리를 설치해줍니다
# yarn
yarn add -D @svgr/webpack

# npm
npm install -D @svgr/webpack

**
2. next.config.js 를 아래와 같이 웹팩 설정을 추가해줍니다.
이 웹팩이 코드를 build할 때 svg 파일을 자동으로 리액트 컴포넌트화 해준답니다!

const nextConfig = {
  reactStrictMode: true,
  webpack: config => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ["@svgr/webpack"],
    });

    return config;
  },
};

module.exports = nextConfig;
import LogoSVG from "public/assets/logo.svg";

const Header = () => {
  return (
    <div>
      <LogoSVG />
    </div>
  );
};

export default Header;

🧐 위 방법도 되지 않는다면 ...

2. Image tag 사용하기

import Image from 'next/image';
import LeftBtnSVG from '../../public/assets/icons/leftBtn.svg';

<Image src={LeftBtnSVG} alt="leftBtn" width={35} />

이런 식으로 Image 태그를 사용하여 src 안에 넣어주는 방법이 있다!

profile
모든 익숙함에 물음표 더하기

0개의 댓글