1. 폰트 적용
폰트 파일은 public 폴더 내부에 넣어
index.css로 다음과 같이 설정해주자.
@font-face {
font-family: "NanumPenScript";
src: url("/NanumPenScript-Regular.ttf");
}
body * {
font-family: "NanumPenScript";
}2. 이미지 불러오기
이미지 파일은 src/assets 폴더 내부에 넣어주자.
그리고 이미지를 사용하는 곳에서 불러와주자.
import emotion1 from "./assets/emotion1.png";
import emotion2 from "./assets/emotion2.png";
import emotion3 from "./assets/emotion3.png";
import emotion4 from "./assets/emotion4.png";
import emotion5 from "./assets/emotion5.png";사용할 땐 경로를 나타내는 src 속성에 지정한 이름으로
넣어줄 수 있다.
<div>
<img src={emotion1} alt="" />
<img src={emotion2} alt="" />
<img src={emotion3} alt="" />
<img src={emotion4} alt="" />
<img src={emotion5} alt="" />
</div>;✅ 이미지 파일을 src 경로에 두는 이유
이미지 파일을 해당하는 경로에 넣어두는 이유는
vite가 내부적으로 설정하는 이미지 최적화 때문이다.
개발자 모드로 앱을 실행할 땐 차이가 없어보이나
배포하여 실행해보면 차이를 확인할 수 있다.
public 경로에 이미지를 넣고 렌더링 할때는
src에 경로를
/emotion1 이런식으로 넣게 되는데이 경우엔 최적화 되지 않는다.
이미지가 최적화됨은 데이터 URI 포맷으로 이미지
주소를 설정하는 것을 말한다.
이 방법은 이미지가 처음 불러와 진 후에는
문자열 형태로 브라우저에 캐싱되기 때문에
새로고침을 해도 새로 불러와지지 않는다.
이러한 방법은 요청 후에 페이지가 렌더링 되는 속도를
보다 빠르게 만든다는 장점이 있다.
⚠️ 이미지가 많은 경우에는
이미지가 많은 경우에는 브라우저 메모리에 과부하가 올 수 있다.
따라서 너무 많은 이미지같은 경우에는 src경로가 아닌
public에 두도록 하자.
1. 이미지 모듈 만들기
이미지를 여러 페이지에서 사용하는 경우에는
각 컴포넌트마다 이미지를 불러오는 import문을
번거롭게 작성해야한다.
이러한 문제를 개선하기 위해 이미지를 불러오는
모듈을 만들어보자.
src 경로 바로 아래에 util이라는 디렉토리를 만들고
해당하는 경로에 get-emotion-image.js라는 파일을 만들어주자.
아까 작성했던
import문을 그대로 복사해서 붙여넣고경로를 수정해주자.
import emotion1 from "./../assets/emotion1.png";
import emotion2 from "./../assets/emotion2.png";
import emotion3 from "./../assets/emotion3.png";
import emotion4 from "./../assets/emotion4.png";
import emotion5 from "./../assets/emotion5.png";그리고 이미지를 이미지 번호 기준으로 반환해주는 함수를 만들어주자.
emotionId를 매개변수로 받아 swich문으로 각각의이모지가 잘 반환될 수 있도록 설정하고 마지막에
그 밖의 요청은
null을 돌려주도록 설정하자.마지막으로 함수 선언의 가장 앞에
export를 붙여내보내주도록 하자.
export function getEmotionImage(emotionId) {
switch (emotionId) {
case 1:
return emotion1;
case 2:
return emotion2;
case 3:
return emotion3;
case 4:
return emotion4;
case 5:
return emotion5;
default:
return null;
}
}이미지를 사용할 컴포넌트에서 해당 함수를 불러오자.
import { getEmotionImage } from "./util/get-emotion-image";
다음으로 함수를 호출하여 각각의 번호를 넣어주면 된다.
<div>
<img src={getEmotionImage(1)} alt="" />
<img src={getEmotionImage(2)} alt="" />
<img src={getEmotionImage(3)} alt="" />
<img src={getEmotionImage(4)} alt="" />
<img src={getEmotionImage(5)} alt="" />
</div>;3. 레이아웃 설정
html,
body {
margin: 0;
width: 100%;
background-color: rgb(246, 246, 246);
}
#root {
background-color: white;
max-width: 600px;
width: 100%;
margin: 0 auto;
min-height: 100vh;
height: 100%;
box-shadow: rgba(100, 100, 100, 0.2) 0 0 29px 0;
}Share article