Gatsby
는 이미지를 정적 파일로 변환하여 최적화하는 플러그인을 가지고 있다.
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;
gatsby-plugin-image
의 StaticImage
컴포넌트를 사용한다.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
를 사용한다.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
}
}
}
}
}
`;