[Gatsby] with Image

찐새·2022년 12월 4일
1

Gatsby

목록 보기
4/6
post-thumbnail

Gatsby는 이미지를 정적 파일로 변환하여 최적화하는 플러그인을 가지고 있다.

install

  • npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp
  • config에 플러그인을 추가한다.
// gatsby-config.ts
import type { GatsbyConfig } from "gatsby";

const config: GatsbyConfig = {
  // (...)
  plugins: [
	`gatsby-plugin-image`,
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
  ],
};

export default config;

usage

StaticImage

  • 이미지를 미리 알고 수동으로 입력할 때는 gatsby-plugin-imageStaticImage 컴포넌트를 사용한다.
import { StaticImage } from "gatsby-plugin-image";
import React from "react";

export default function IndexPage() {
  return (
    <div>
      <StaticImage
    	height={500}
        src="https://images.unsplash.com/photo-1633533452206-8ab246b00e30?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1031&q=80"
        alt="Stickers"
      />
    </div>
  );
}
  • unsplash의 이미지 주소를 사용했지만 엘리멘트는 다른 주소를 가진다.

  • img 태그가 아닌 여러 태그로 감싸져 있고, 주소가 다른 것이 보인다.
  • 이미지를 로드할 때 webp으로 변환해 정적 이미지를 생성한다.
  • 설정한 사이즈에 따라 고용량의 이미지를 알맞게 최적화한다.

  • 로드가 느린 상황에서는 이미지에서 가장 많이 사용한 색을 이미지의 placeholder로 삼고, 이미지를 보여준다.

GatsbyImage

  • 이미지를 자동으로 삽입할 때는 GatsbyImage를 사용한다.
import React from "react";
import { GatsbyImage, getImage } from "gatsby-plugin-image";

export default function BlogPost({ data, children }) {
  const image = getImage(
    data.mdx?.frontmatter?.headerImage?.childImageSharp?.gatsbyImageData!
  );
  return (
    <div>
      <GatsbyImage image={image as any} alt={data.mdx?.frontmatter?.title!} />
      <div>{children}</div>
    </div>
  );
}
  • 예시로 사용한 이미지는 mdx 파일의 frontmatter에 추가한 headerImage를 통해 가져왔다.
  • mdx파일과 같은 폴더에 이미지를 추가한 후 파일명과 확장자를 headerImage에 추가한다.
---
title: Hello everyone
category: personal
date: "2022-12-03"
author: JS
slug: hello-everyone
headerImage: flower.jpg
---

import Temp from "../../src/components/temp";

# Hello everyone!

<Temp />

⏫컴포넌트를 렌더링한 모습⏫
  • mdx에 담긴 이미지는 쿼리에서 mdx➡frontmatter➡childImageSharp➡gatsbyImageData로 가져온다.
import { graphql } from "gatsby";

export default function PostDetail({ data, children }) {
  // (...)
}

export const query = graphql`
  query PostDetail($frontmatter__slug: String) {
    mdx(frontmatter: { slug: { eq: $frontmatter__slug } }) {
      frontmatter {
		(...)
        headerImage {
          childImageSharp {
            gatsbyImageData
          }
        }
      }
    }
  }
`;

참고
노마드코더 - 리액트JS 마스터 클래스
gatsby-plugin-image

profile
프론트엔드 개발자가 되고 싶다

0개의 댓글