본문 바로가기

TypeScript 끄적끄적

tsx로 컴포넌트를 만들고 png이미지를 import할때 오류 해결 방법

728x90

webpack에서 이미지도 번들링 해주려고, 아래와 같이 설정을 해주니 typescript 쪽에서 해당 에러가 발생했다.

// webpack.config.js
...
      {
        test: /\.(png|jpe?g)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[path][name].[ext]',
          },
        },
      },
...

 

 

TS2307: Cannot find module './이름.png' or its corresponding type declarations.

 

원인은 타입이 정의되어 있지 않아서 이다. Typescript에서 .d.ts 파일을 추가해줘서 타입을 추가할 수 있다. (단, index.d.ts 파일은 index.ts 파일이 생성했다고 Typescript가 추측해서 무시된다. 따라서 images.d.ts 와같이 다른 이름을 지어주자!)

 

// tsconfig.json
...
"typeRoots": ["src/types"],
...

 

// src/types/images.d.ts
declare module '*.png';
declare module '*.jpg';
declare module '*.jpeg';

문제는 해당 파일 끄면 오류가 나시 나옴..

음 일단은 잘작동하니 넘어가기로 함..

 

빨간색 오류 밑줄이 사라지고 해결 됩니다!

728x90