본문 바로가기

Front-End

Next - 이미지 최적화 ( Image Component and Image Optimization )

사이트 성능 측정을 하였더니, 로딩 속도에 문제가 많아 이미지 최적화 작업을 진행하게 되었습니다.

아래 사진은 제가 개발한 사이트의 속도입니다.

그러던 중 Next 에서 제공해주는 Image 태그를 알게 되었고, 이를 통해 개선을 해보았습니다.공식 문서 : https://nextjs.org/docs/basic-features/image-optimization 를 참고하여 진행하였습니다.

 

next/image 란?

built-in 성능을 최적화 하기 위해 <img>를 확장한 next.js image 컴포넌트입니다. 이 컴포넌트는 Core Web Vitals 에서 좋은 점수를 얻게 도와줍니다. 이 점수는 구글 SEO에 중요한 역할을 합니다. ( 링크 )

 

  • Improved Performance : modern image formats을 사용하여 각각 디바이스에 맞는 적절한 크기를 항상 제공해줌
  • Visual Stability : 자동적으로 Cumulative Layout Shift 되지 않도록 해줌
  • Faster Page Loads : 뷰포트에 들어갈때만 이미지는 로드됨
  • Asset Flexibility : remote servers에 저장된 이미지도 resize 할 수 있음
import Image from 'next/image'

 

Local images

import profilePic from '../public/me.png'

로컬 이미지를 사용하기 위해서는 jpg, png, webp 파일을 import하면 됩니다. Next.js가 자동으로 width, heigth를 계산해줍니다. 
덕분에 이미지가 로딩되는 동안 Cumulative Layout Shift를 방지해줍니다.

import Image from 'next/image'
import profilePic from '../public/me.png'

function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src={profilePic}
        alt="Picture of the author"
        // width={500} automatically provided
        // height={500} automatically provided
        // blurDataURL="data:..." automatically provided
        // placeholder="blur" // Optional blur-up while loading
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}

Remote Images

Remote image인 경우엔 Next.js 가 build 시점에 remote file에 접근할 수 없습니다. 그렇기 떄문에 width, heigth를 필수로 입력해주어야 합니다.

import Image from 'next/image'

export default function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src="/me.png"
        alt="Picture of the author"
        width={500}
        height={500}
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}

Domains

remote image에 접근하기 위해서는 아래와 같이 설정해주어야 합니다.

// next.config.js
module.exports = {
  images: {
    domains: ['example.com', 'example2.com'],
  },
}

Priority

Largest Contentful Paint element에 priority property 를 추가해주어야 합니다.이 속성은 Next.js가 이미지 로딩을 우선시해줍니다. 

( 우선시 해주면 왜 빠른건지는 아직 이해 못함 )

import Image from 'next/image'

export default function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src="/me.png"
        alt="Picture of the author"
        width={500}
        height={500}
        priority
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}

Image Sizing

layout shift는 대표적으로 성능을 망치는 이유중 하나입니다. ( Cumulative Layout shift ) 해당 문제를 피할 수 있는 방법은 이미지의 size를 항상 명시해주는 것입니다. 브라우저가 페이지 로딩전에 정확한 공간을 미리 할당할 수 있기 때문입니다.

 

next/image에 크기를 명시하는 방법은 3가지가 있습니다.

  1. static import 를 사용하기
  2. remote 이미지를 사용하는 경우, heigth, width 속성 표기
  3. layout='fill' 사용해서 부모 element 크기와 맞추기 ( 이미지 크기를 모르는 경우 사용 )