[React + Vite] svgr 세팅하기

마리 Mari·2024년 2월 14일
post-thumbnail

작업하고 있던 사이드 프로젝트의 환경을 CRA에서 Vite로 옮겨보던 중, svgr 관련해서 오류가 났다. stackoverflow에 나온 방법을 따라봤는데도 해결이 안되어서 삽질을 하다, 공식문서를 보고 해결했다.

결론부터 말하자면

결론

v.4 이상이라면?

  1. default로 import하기

  2. 파일명 뒤에 ?react 붙이기

import Logo from "@/assets/logo.svg?react";

const Header = () => (
  <div>
    <Logo />
  </div>
)};

v.4 이하

import { ReactComponent as Logo } from "@/assets/logo.svg";

const Header = () => (
  <div>
    <Logo />
  </div>
)};

그 외 기본적으로 해야하는 작업

  1. vite.config.js 수정

    import svgr from "vite-plugin-svgr";
    
    export default {
      // ...
      plugins: [svgr()],
    };
  2. client type 추가

    2-1 vite-env.d.ts에 추가하기

    /// <reference types="vite-plugin-svgr/client" />

    2-2. tsconfig에 추가하기

    {
      "compilerOptions": {
        "types": ["vite/client"]
      }
    }



Client Type?

client type의 역할이 무엇인지 정확하게 이해가 되지 않아서 살짝 찾아보았다.

Vite 공식문서에서는 vite가 Node.js Api의 type을 default로 사용하기 때문에, client 환경 코드의 타입을 채워주기 위해 작성해야한다고 설명한다.

Vite's default types are for its Node.js API. To shim the environment of client side code in a Vite application, add a d.ts declaration file.
Alternatively, you can add vite/client to compilerOptions.types inside tsconfig.json
출처-Vite 공식문서

기술적으로 명확하게 이해되지 않아서 다른 자료도 찾아보았다.

우선 일반 주석이라고 생각했던 ///triple slash directives(트리플 슬래시 지시어)라는 이름이 있는 다른 종류의 주석이었다. 단일 XML 태그를 포함한 한 줄 주석이며, 주석의 내용이 타입스크립트 컴파일러 지시어로 사용된다.

이를 통해 타입스크립트 컴파일러가 추가 파일을 컴파일 과정에 포함할 수 있다.
typescript 공식문서 설명: https://www.typescriptlang.org/ko/docs/handbook/triple-slash-directives.html


tsconfig의 compilerOptions.types도 이와 비슷한 역할이다. types에 list된 package는 compile시 global scope에 포함된다고 한다.
typescript 공식문서 설명: https://www.typescriptlang.org/ko/tsconfig#types




요즘 You don't know JS yet을 읽고있는데, 새삼 난 JS도 TS도 명확하게 알지 못하는 부분이 많구나 체감한다.
앞으로 더 꼼꼼하게 찾아보며 공부해야겠다.


참고자료

profile
우리 블로그 정상영업합니다.

0개의 댓글