Created
April 16, 2019 12:43
-
-
Save chendo/0f6ba6df171c08a4c8f435dad2fcffd9 to your computer and use it in GitHub Desktop.
Critical CSS support for both styled-components and Emotion in Next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Document, { Head, Main, NextScript } from 'next/document' | |
import { ServerStyleSheet } from 'styled-components' | |
import { renderToString } from 'react-dom/server' | |
import { extractCritical } from 'emotion-server' | |
export default class MyDocument extends Document { | |
static async getInitialProps(ctx) { | |
const sheet = new ServerStyleSheet(); | |
const originalRenderPage = ctx.renderPage | |
try { | |
let emotionCriticalCSS | |
ctx.renderPage = () => | |
originalRenderPage({ | |
enhanceApp: App => ( | |
props => { | |
const styledComponentsData = sheet.collectStyles(<App {...props} />) | |
emotionCriticalCSS = extractCritical(renderToString(styledComponentsData)).css | |
return styledComponentsData | |
} | |
) | |
}) | |
const initialProps = await Document.getInitialProps(ctx) | |
return { | |
...initialProps, | |
styles: ( | |
<React.Fragment> | |
{initialProps.styles} | |
<style>{emotionCriticalCSS}</style> | |
{sheet.getStyleElement()} | |
</React.Fragment> | |
) | |
} | |
} finally { | |
sheet.seal() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment