ERROR ๐Ÿšจ Cannot find module image file(svg, png)

hotbreakbยท2022๋…„ 6์›” 11์ผ
0

๋ฆฌ์•กํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๋‹ค๊ฐ€ ์ •๋ง ๋œฌ๊ธˆ์—†๋Š” ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค.

์ด์ œ๊นŒ์ง€ ์ž˜ ์ฝ๊ณ  ์žˆ์—ˆ์ž–์•„. ์™œ ๊ฐ‘์ž๊ธฐ ์—†๋‹ค๋Š” ๊ฑฐ์—ฌ? ์›์ธ์€ ์•„์ง๊นŒ์ง€ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ ํ•ด๊ฒฐ์ฑ…์€ ์ฐพ์•˜๋‹ค.

๋ฐฉ๋ฒ•

src ์•ˆ์— custom.d.ts๋ฅผ ๋งŒ๋“ ๋‹ค. (์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ํ”„๋กœ์ ํŠธ๋ผ๋ฉด .js๋กœ ๋งŒ๋“ ๋‹ค)

declare module '*.svg' {
    const content: any;
    export default content;
}

declare module "*.png" {
    const value: any;
    export = value;
}

์ถ”๊ฐ€ํ•˜๋ฉด ์ œ๋Œ€๋กœ ์ธ์‹๋œ๋‹ค.

๋ฌธ์ œ๋Š” svg ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์ด ๋ฐ”๋€๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ์›๋ž˜๋Š” {ReactComponent as Siren} ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ ์ € ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ•œ ๋’ค๋กœ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ธ์‹ํ•˜์ง€ ๋ชปํ•œ๋‹ค.

import Siren from "../../assets/images/button/siren.svg";
const StyledSiren = styled.button`
  width: 24px;
  height: 24px;
  background-image: url(${Siren});
  background-size: contain;
  background-repeat: no-repeat;
`;
background-image url์ด๋‚˜ img content๋กœ ์„ค์ •ํ•˜์—ฌ ์‚ฌ์šฉํ•œ๋‹ค.

๋งŒ์•ฝ ์ปดํฌ๋„ŒํŠธ๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ณ€๊ฒฝํ•œ๋‹ค.

declare module '*.svg' {
    import { ReactElement, SVGProps } from "react";
    const content: (props: SVGProps<SVGElement>) => ReactElement;
    export default content;
}
๐Ÿšจ Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided 

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋˜ ์—๋Ÿฌ๊ฐ€ ๋‚  ๊ฒƒ์ด๋‹ค. ์ด๋Ÿด ๋•Œ๋Š” svg๋ฅผ ์ปดํฌ๋„ŒํŠธ๋กœ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

import React from "react";

const Logo = props =>
  <svg > 
.... svg code
  </svg>;

export default Logo;

์ด๊ฒŒ ๊ท€์ฐฎ์œผ๋ฉด svgr์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

profile
๊ธ€์Ÿ์ด ํ”„๋ก ํŠธ ๊ฐœ๋ฐœ์ž, ํ—ฌ๋ Œ์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€