목표
/content/blog/2019-09-29—xx/index.md 문서에서
대표 이미지로
동일 폴더 안의 이미지를 사용하고 싶다.
검색
gatsby.org 로 가서 markdown 검색 Working With Images in Markdown Posts and Pages 로 이동
이 페이지를 보면 위와 아래 내용이 다르다.
- 위쪽 내용은 index.md의 상단에 메타정보에 이미지 경로를 지정해 두고,
포스트의 메인 이미지로 사용하는 방법 - 아래 내용은 마크다운 문서 내에서 inline 으로 이미지를 사용하는 방밥이다.
해당 포스트는 1번에 해당
메타정보에 대문 이미지 지정하기
1. plugin 설치
npm install --save gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp
2. gatsby-config.js
file system 내 파일을 사용한다는 설정. 초기에 이미 셋팅되어 있음.
module.exports = {
plugins: [
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
`gatsby-transformer-remark`,
...
{
resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/content/blog`, // post 위치 }, },
],
}
3. index.md
index.md 와 동일 폴더 안에 (src/content/blog/문서경로)
jenkins-blog-image.jpg 이미지를 넣어 놓고
메타정보에 featuredImage: jenkins-blog-image.jpg
추가
# src/content/blog/문서경로/index.md
---
title: "title"
...
featuredImage: jenkins-blog-image.jpg---
4. blog-post.js 의 graphql 수정
src/templates/blog-post.js 안의 graphql 으로 blog 들의 index.md 파일들을 조회한다.
그 데이터를 BlogPostTemplate 을 html 파일로 변환하면서 꽃아준다.
template 내에 image 위치가 고정되어 있음.
// src/templates/blog-post.js
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import Img from "gatsby-image"
export default ({ data }) => {
let post = data.markdownRemark
let featuredImgFluid = post.frontmatter.featuredImage.childImageSharp.fluid return (
<Layout>
<div>
<h1>{post.frontmatter.title}</h1>
<Img fluid={featuredImgFluid} /> <div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
</Layout>
)
}
export const query = graphql`
query PostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
featuredImage { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } }
}
}
`