_document.tsx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document';
  2. import React from 'react';
  3. import { ServerStyleSheet } from 'styled-components';
  4. // https://github.com/vercel/next.js/blob/master/examples/with-styled-components/pages/_document.js
  5. export default class CustomDocument extends Document {
  6. static getInitialProps = async (context: DocumentContext) => {
  7. const sheet = new ServerStyleSheet();
  8. const originalRenderPage = context.renderPage;
  9. try {
  10. context.renderPage = () =>
  11. originalRenderPage({
  12. enhanceApp: (App) => (props) => {
  13. return sheet.collectStyles(<App {...props} />);
  14. },
  15. });
  16. const initialProps = await Document.getInitialProps(context);
  17. return {
  18. ...initialProps,
  19. styles: [React.Children.toArray(initialProps.styles), sheet.getStyleElement()],
  20. };
  21. } finally {
  22. sheet.seal();
  23. }
  24. };
  25. render() {
  26. return (
  27. <Html lang="en">
  28. <Head />
  29. <body>
  30. <Main />
  31. <NextScript />
  32. </body>
  33. </Html>
  34. );
  35. }
  36. }