반응형
gatsby-plugin-image
gatsby-plugin-image를 사용해서 gatsby 이미지를 최적화하는 방법을 알아보자.
설치 하기
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp
설정 파일
gatsby-config.js
파일에서 plugin에 추가 해준다.
module.exports = {
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`, // 동적 이미지 생성을 위해서 필요함
],
}
정적인 이미지 Static Image 사용 시
import { StaticImage } from "gatsby-plugin-image"
export function Dino() {
return <StaticImage src="../images/dino.png" alt="A dinosaur" />
}
gatsby-plugin-image
에서 제공하는 StaticImage 컴포넌트를 사용해서 렌더링 하면 된다.
StaticImage 이미지 경로와 alt 값을 props로 전달하고
원격 서버(CDN)에 있는 이미지 또한 마찬가지고 URL를 넘겨 준다.
해당 컴포넌트가 gatsby 빌드 시 최적화된 이미지로 자동으로 변환된다.
import { StaticImage } from "gatsby-plugin-image"
export function Dino() {
return (
<StaticImage
src="../images/dino.png"
alt="A dinosaur"
placeholder="blurred"
layout="fixed"
width={200}
height={200}
/>
)
}
이미지 크기 등의 옵션도 props로 넘겨서 custom해줄수 있다.
https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-plugin-image/#staticimage
동적인 이미지 Dynamic Image 사용 시
gatsby에서 query 등으로 가져오는 동적인 이미지를 렌더링 할 시 사용
query 작성 시
childImageSharp childImageSharp 를 사용 한다
query {
blogPost(id: { eq: $Id }) {
title
body
avatar {
childImageSharp {
childImageSharp(width: 200)
}
}
}
}
custom
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
위 처럼 query에서 옵션을 줄 수 있다
렌더링 시
GatsbyImage 컴포넌트를 사용 한다
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
const image = getImage(data.blogPost.avatar)
return (
<section>
<h2>{data.blogPost.title}</h2>
<GatsbyImage image={image} alt={data.blogPost.author} />
<p>{data.blogPost.body}</p>
</section>
)
}
export const pageQuery = graphql`
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
주의
formats
기본 값이 webp 이지만 IE에서는 지원이 되지 않기 떄문에 IE를 지원해야 된다면 [auto, png, jpg] 등으로 변경 해준다.
ㅈ참고 사이트 : https://www.gatsbyjs.com/plugins/gatsby-plugin-image/
반응형
'개발관련' 카테고리의 다른 글
개츠비 gatsby.js AWS S3에 업로드해서 정적 사이트 호스팅 하기 (0) | 2021.10.23 |
---|---|
AWS S3와 E2C의 차이 (0) | 2021.10.12 |
안드로이드 AlertDialog 바깥영역 클릭해서 취소 하기 setOnCancelListener (0) | 2021.06.10 |
Android Kotlin 안드로이드 코틀린 AlertDialog Dismiss 설정하기 ( Alert 콜백 처리) (0) | 2021.05.28 |
IOS 앱 개발할때 테스트 시 테스트 플라이트( TestFlight )로 테스트 하는 방법 (0) | 2021.04.16 |