Next.js @svgr/webpack Cannot find module 에러

yejiiha·2024년 1월 12일
0

Next.js 에서 svg 이미지를 컴포넌트로 사용하기 위해 @svgr/webpack을 사용 중이었다.

일반 컴포넌트만 사용을 하려면 이렇게 코드를 작성하면 된다.

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

    return config;
  },
};

module.exports = nextConfig;

그런데 작업을 하다 보니 컴포넌트 말고 url로도 사용을 하고 싶어졌다..!!!

@svgr/webpack 공식문서를 확인해 보니 이렇게 next.config.js를 수정하면 된다고 해서 수정했다.

module.exports = {
  webpack(config) {
    // Grab the existing rule that handles SVG imports
    const fileLoaderRule = config.module.rules.find((rule) =>
      rule.test?.test?.('.svg'),
    )

    config.module.rules.push(
      // Reapply the existing rule, but only for svg imports ending in ?url
      {
        ...fileLoaderRule,
        test: /\.svg$/i,
        resourceQuery: /url/, // *.svg?url
      },
      // Convert all other *.svg imports to React components
      {
        test: /\.svg$/i,
        issuer: fileLoaderRule.issuer,
        resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
        use: ['@svgr/webpack'],
      },
    )

    // Modify the file loader rule to ignore *.svg, since we have it handled now.
    fileLoaderRule.exclude = /\.svg$/i

    return config
  },

  // ...other config
}

next.config.js를 수정하고 공식문서에 있는 것처럼 이렇게 적용을 해봤다!

import Image from 'next/image'
import starUrl from './star.svg?url'

const Example = () => (
  <div>
    <Image src={starUrl} />
  </div>
)

아니 그런데 나는 Cannot find module './star.svg?url' or its corresponding type declarations.ts(2307) 이 에러가 나왔다 ,,, 😮‍💨

대체 뭘까.. 일반 컴포넌트는 잘 적용이 되는데 왜 그럴까,, 싶었는데 해결방법은 간단했다!

// image.d.ts
declare module '*.svg?url' {
  const content: any;
  export default content;
}

나는 image.d.ts 라는 파일을 만들어서 .svg?url에 대해서 정의를 해줬더니 바로 에러가 사라지고 정상적으로 컴파일 되었다!! ^_^

해결방법은 간단한데 정리된 블로그를 찾지 못해,, 혹시 나처럼 누군가 헤맬 때 도움 되라고 적어봤습니다 ,, ㅎ ㅎ

profile
Frontend Developer

0개의 댓글