Gatsby Custom HTML 사용하기

2022년 10월 13일

Gatsby

# Gatsby# Customizing# HTML

📕 목차

들어가며

Gatsby는 <head> 부분과 다른 HTML을 서버사이드 렌더링하기위해서 React 컴포넌트를 사용한다. 대부분의 경우 기본으로 제공되는 html.js를 사용해도 무방하나 검색 최적화를 위해서 전역적으로 head 삽입하고 싶을 때 유용하게 사용할 수 있다.

html.js 커스터마이징

html.js 파일을 커스터마이징 하기위해서는 기본으로 제공되는 파일을 일단 복사해온다.

cp .cache/default-html.js src/html.js

복사명령어를 통해서 html.js 파일을 복사해왔다면 파일의 내용은 다음과 같다.

import React from "react"
import PropTypes from "prop-types"

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
    </html>
  )
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

위의 코드에서 전역적으로 사용되고 동적으로 업데이트 할 필요없는 경우라면 필요한 정보를 추가해준다. 나는 google search console, naver 웹마스터 도구에서 소유권확인을 위한 메타태그를 삽입하기 위해 사용하였다.

공식문서 상에 다음과 같은 말이 있다.

Customizing html.js is a workaround solution for when the use of the appropriate APIs is not available in gatsby-ssr.js. Consider using onRenderBody or onPreRenderHTML instead of the method above. As a further consideration, customizing html.js is not supported within a Gatsby Theme. Use the API methods mentioned instead.

참고자료

profile

박민기

단순하게 살아라. 현대인은 쓸데없는 절차와 일 때문에 얼마나 복잡한 삶을 살아가는가? - 이드리스 샤흐

© 2023, 미나리와 함께 만들었음