React

img src 태그 오류

느닷 2021. 11. 25. 20:29

import 없이 react 에서 이미지를 표시하기 위해 img src 태그를 사용하면 흔히 얘기하는 엑박이 뜬다.

<img src="../images/slideView.png" alt="" />

 

아주 간단한 문제지만 처음겪는 오류

해결은 다음과 같다.

<img src={require("../images/slideView.png").default} alt="" />

require 와 default 를 코드에 더해주면 문제 해결.

참고로 .default 가 있어야 이미지를 객체가 아닌 이미지 자체로 불러올 수 있다.

-> import 를 사용하거나, 위와 같이 require, default 를 사용하자.

(이미지 하나 때문에 import 를 한 줄씩 추가하지 않기 위한 시도였음) -> 코드스플리팅을 공부해보자.

->> 그리고 import로 모듈을 불러오는 것이 코드량을 줄이고 성능면에서도 효율적이라고 한다. 따라서, 가급적이면 import 하자.

(모듈을 불러올때 사용하지 않는 코드를 웹팩의 tree shaking 으로 빌드 시 제거된다고 함)

 

 

왜 이런 오류가 발생하는지.

CRA로 웹팩을 사용하는 경우, hot module loading 을 제공하기 때문이라고 한다.(아래 링크 참조)

https://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack

 

What exactly is Hot Module Replacement in Webpack?

I've read a few pages about Hot Module Replacement in Webpack. There's even a sample app that uses it. I've read all of this and still don't get the idea. What can I do with it? Is it suppos...

stackoverflow.com

 

웹팩이란?

https://ne-dot.tistory.com/44

 

WebPack

 

ne-dot.tistory.com