ABOUT ME

-

  • [ Next ] webpack 활용 svg icon
    Front/Next 2025. 9. 10. 23:46
    반응형

    next js 에서 svg icon사용할때는 SVG 아이콘을 컴포넌트로 직접 만들어서 사용하는 방법과 webpack을 이용해서

    그냥 사용하는 방법이 있는데

    svg를 추가할때마다 계속 컴포넌트로 만들어주는게 귀찮을 것같고,

    vue처럼 svg icon컴포넌트를 만들까 하다가 지금 진행하는 프로젝트에서는 svg icon을 많이 쓰지는 않을 것같아서 그냥 진행하기로 했다.

     


    Installment

    우선 webpack을 설치

    npm install --save-dev @svgr/webpack

     

    이후 next.config.ts 파일에서 turbopack에 아래 규칙을 넣어준다.

    turbopack을 사용하면 turbopack에 규칙을 넣어줘야하고, turbopack을 사용하지 않으면 webpack에 규칙을 넣어주면 된다.

    import type { NextConfig } from "next";
    
    const nextConfig: NextConfig = {
        devIndicators: false,
        turbopack: {
            rules: {
                '*.svg': {
                    loaders: ['@svgr/webpack'],
                    as: '*.js'
                }
            }
        }
    };
    
    export default nextConfig;

     

    만약 타입스크립트를 사용한다면 svg.d.ts파일을 만들어준다.

    declare module '*.svg' {
        const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
    
        export default ReactComponent
    }

     

    src/types 폴더안에 타입을 만들어주었기 때문에 tsconfig.json에서 해당 src/types를 포함시켜준다.

      "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx",
        ".next/types/**/*.ts",
        "src/types/**/*.d.ts"
      ],

    Useage

    이제 사용알 아이콘 svg파일을 준비해준다.

    사실 아이콘 경로는 크게 중요하지는 않지만 src/icons 폴더를 만들어서 여기 안에서 관리하기로 했다.

     

    svg를 컴포넌트 방식으로 사용하기 때문에 width height 와  path에있는 fill 이나 stroke를 각 path에서 제거해주었다.

    path에 stroke값이 존재하면 style로 stroke 색상을 줘도 path부분은 바뀌지 않아서

    style 속성을 줘야할 부분들은 svg쪽으로 빼주었다.

     

    <svg width="current" height="current" viewBox="0 0 24 24" fill="none" stroke="#ffffff" xmlns="http://www.w3.org/2000/svg">
        <path d="M8.5 19H8C4 19 2 18 2 13V8C2 4 4 2 8 2H16C20 2 22 4 22 8V13C22 17 20 19 16 19H15.5C15.19 19 14.89 19.15 14.7 19.4L13.2 21.4C12.54 22.28 11.46 22.28 10.8 21.4L9.3 19.4C9.14 19.18 8.77 19 8.5 19Z" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M15.9965 11H16.0054" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M11.9955 11H12.0045" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M7.99451 11H8.00349" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>

     

    이후 해당 svg파일을 import해서 사용하면 된다.

    import MessageIcon from '@/icons/message.svg';
    
    <MessageIcon width={20} height={20} style={{ stroke: 'red' }}/>

     

     

    그럼 이런식으로 내가 원하는 크기와 색이 적용된 아이콘이 나오는 것을 확인할 수 있다.

    728x90
    반응형