Nextjs 加载 styled-components 丢失样式问题

588 阅读1分钟

今天在部署 nextjs 项目的时候,发现一个问题:通过域名打开网站时,会有短时间的样式丢失问题,网站样式在打开网页的瞬间丢失,然后在短时间内又恢复。

排查问题

那么接下来就开始排查问题:

1、是否是 css 样式文件加载过慢导致的

2、哪些样式文件丢失了

排查结果

排查结果:

1、css 文件加载速度并不存在问题

2、丢失的样式都是通过 styled-components 写入的

分析原因并寻找解决方法

为什么 styled-components 样式在网页打开之前没有注入到页面中呢?

这类型的 css 应该是提前注入页面中,提前加载好的。

在阅读了这篇文章后,找到了解决方法:medium.com/swlh/server…

需要在 pages 目录下,创建一个 _document.tsx 文件,然后写入

import Document, { DocumentContext } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps (ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }
}

至此,我们就解决了 styled-components 无法提前加载的问题。