1- import Document , { Head , Html , Main , NextScript } from "next/document" ;
1+ import Document , { Html , Head , Main , NextScript } from "next/document" ;
22import createEmotionServer from "@emotion/server/create-instance" ;
3- import React from "react " ;
4- import createCache from "@emotion/cache " ;
3+ import createEmotionCache from "./createEmotionCache " ;
4+ import * as React from "react " ;
55
66export default class MyDocument extends Document {
7- static async getInitialProps ( ctx : any ) {
8- const originalRenderPage = ctx . renderPage ;
9-
10- const cache = createCache ( { key : "css" , prepend : true } ) ;
11- const { extractCriticalToChunks } = createEmotionServer ( cache ) ;
12-
13- ctx . renderPage = ( ) =>
14- originalRenderPage ( {
15- enhanceApp : ( App : any ) =>
16- function EnhanceApp ( props : any ) {
17- return < App emotionCache = { cache } { ...props } /> ;
18- } ,
19- } ) ;
20-
21- const initialProps = await Document . getInitialProps ( ctx ) ;
22- const emotionStyles = extractCriticalToChunks ( initialProps . html ) ;
23- const emotionStyleTags = emotionStyles . styles . map ( ( style ) => (
24- < style
25- data-emotion = { `${ style . key } ${ style . ids . join ( " " ) } ` }
26- key = { style . key }
27- dangerouslySetInnerHTML = { { __html : style . css } }
28- />
29- ) ) ;
30-
31- return {
32- ...initialProps ,
33- styles : [ ...React . Children . toArray ( initialProps . styles ) , ...emotionStyleTags ] ,
34- } ;
35- }
367 render ( ) {
378 return (
389 < Html lang = "en" >
@@ -45,3 +16,32 @@ export default class MyDocument extends Document {
4516 ) ;
4617 }
4718}
19+
20+ MyDocument . getInitialProps = async ( ctx ) => {
21+ const originalRenderPage = ctx . renderPage ;
22+
23+ const cache = createEmotionCache ( ) ;
24+ const { extractCriticalToChunks, constructStyleTagsFromChunks } = createEmotionServer ( cache ) ;
25+
26+ ctx . renderPage = ( ) =>
27+ originalRenderPage ( {
28+ enhanceApp : ( App : any ) =>
29+ function EnhanceApp ( props ) {
30+ return < App emotionCache = { cache } { ...props } /> ;
31+ } ,
32+ } ) ;
33+
34+ const initialProps = await Document . getInitialProps ( ctx ) ;
35+ const emotionChunks = extractCriticalToChunks ( initialProps . html ) ;
36+ const emotionStyleTags = constructStyleTagsFromChunks ( emotionChunks ) ;
37+
38+ return {
39+ ...initialProps ,
40+ styles : (
41+ < >
42+ { initialProps . styles }
43+ < style data-emotion = { `css` } dangerouslySetInnerHTML = { { __html : emotionStyleTags } } />
44+ </ >
45+ ) ,
46+ } ;
47+ } ;
0 commit comments