Custom ` Document ` - team-wedev/wedev GitHub Wiki

Custom <Document>

Custom <Document>λŠ” 보톡 μ‚¬μš©μžμ˜ μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ <html> κ³Ό <body> νƒœκ·Έλ“€μ„ ν™•μž₯μ‹œν‚¬ λ•Œ μ‚¬μš©ν•©λ‹ˆλ‹€. Next.js νŽ˜μ΄μ§€λ“€μ€ document의 μ£Όλ³€ markup μ •μ˜λ₯Ό κ±΄λ„ˆλ›°κΈ° λ•Œλ¬Έμ— μ΄λŸ¬ν•œ μž‘μ—…μ΄ ν•„μš”ν•©λ‹ˆλ‹€.

μ΄λŠ” μ‚¬μš©μžμ—κ²Œ css-in-JS λΌμ΄λΈŒλŸ¬λ¦¬λ“€(styled-components or emotion)에 λŒ€ν•œ server-side rendering을 지원할 수 있게 ν•©λ‹ˆλ‹€.

Custom <Document>λŠ” λ˜ν•œ 비동기 μ„œλ²„ λ Œλ”λ§ 데이터λ₯Ό ν‘œν˜„ν•˜λŠ” getInitialProps λ₯Ό ν¬ν•¨ν•©λ‹ˆλ‹€.

Note: <Document>의 getInitialProps λŠ” client-side transitionμ΄λ‚˜ νŽ˜μ΄μ§€κ°€ automatically statically optimized 된 κ²½μš°μ—μ„œ ν˜ΈμΆœλ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

Custom <Document>λ₯Ό μ‚¬μš©ν•˜κΈ° μœ„ν•΄μ„œ μ‚¬μš©μžλŠ” λ°˜λ“œμ‹œ ./pages/_document.js νŒŒμΌμ„ λ§Œλ“€μ–΄μ•Ό ν•©λ‹ˆλ‹€. 그리고 Document 클래슀λ₯Ό extends ν•΄μ•Ό ν•©λ‹ˆλ‹€.

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

<Html>, <Head/>, <Main />, <NextScript /> λŠ” λͺ¨λ‘ νŽ˜μ΄μ§€κ°€ λ Œλ”λ§ λ˜λŠ”λ°μ— ν•„μš”ν•œ μš”μ†Œλ“€μž…λ‹ˆλ‹€.

<Main /> 외뢀에 μœ„μΉ˜ν•œ React-component듀은 λΈŒλΌμš°μ €μ— μ˜ν•΄μ„œ μ΄ˆκΈ°ν™”λ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜ λ‘œμ§μ„ 여기에 λ”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€. λ§Œμ•½ λͺ¨λ“  νŽ˜μ΄μ§€μ—μ„œ κ³΅μœ λ˜μ–΄μ•Όν•˜λŠ” μ»΄ν¬λ„ŒνŠΈκ°€ 생기면, <App> componentλ₯Ό λŒ€μ‹  μ΄μš©ν•˜μ‹­μ‹œμ˜€.

ctx κ°μ²΄λŠ” λͺ¨λ“  getInitialProps hook μ—μ„œ μˆ˜μ‹ λœ 객체와 λ™μΌν•˜λ©°, ν•˜λ‚˜λ§Œ μΆ”κ°€λ©λ‹ˆλ‹€. - renderPage(Funcion)은 μ‹€μ œ React λ Œλ”λ§ λ‘œμ§μ„ μ‹€ν–‰ν•˜λŠ” μ½œλ°±μž…λ‹ˆλ‹€. μ΄λŠ” Aphrodite의 renderStaticκ³Ό 같은 μ„œλ²„μ‚¬μ΄λ“œ λ Œλ”λ§μ„ 도와주기 μœ„ν•œ ν•¨μˆ˜λ₯Ό decorateν•˜κΈ°μ— μ ν•©ν•©λ‹ˆλ‹€.

Customizing renerPage

μ—¬λŸ¬λΆ„μ΄ renderPageλ₯Ό μ‚¬μš©μž μ •μ˜ν•΄μ•Όν•˜λŠ” μœ μΌν•œ μ΄μœ λŠ” μ„œλ²„ λ Œλ”λ§κ³Ό μ˜¬λ°”λ₯΄κ²Œ μž‘λ™ν•˜λ„λ‘ μ‘μš© ν”„λ‘œκ·Έλž¨μ„ λž©ν•‘ν•΄μ•Όν•˜λŠ” css-in-js λΌμ΄λΈŒλŸ¬λ¦¬μ—μ„œ μ‚¬μš©ν•˜κΈ°μœ„ν•œ κ²ƒμž…λ‹ˆλ‹€.

import Document from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const originalRenderPage = ctx.renderPage

    ctx.renderPage = () =>
      originalRenderPage({
        // useful for wrapping the whole react tree
        enhanceApp: App => App,
        // useful for wrapping in a per-page basis
        enhanceComponent: Component => Component,
      })

    // Run the parent `getInitialProps` using `ctx` that now includes our custom `renderPage`
    const initialProps = await Document.getInitialProps(ctx)

    return initialProps
  }
}

export default MyDocument
⚠️ **GitHub.com Fallback** ⚠️