Custom ` Document ` - team-wedev/wedev GitHub Wiki
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νκΈ°μ μ ν©ν©λλ€.
μ¬λ¬λΆμ΄ 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