首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加载样式需要时间- Next.js

问加载样式需要时间- Next.js
EN

Stack Overflow用户
提问于 2022-10-29 01:59:14
回答 1查看 75关注 0票数 -1

当我输入我的投资组合时,它会加载未样式的html页面,并且只在几秒钟后加载样式。我怎么解决这个问题?

注意:我使用的是样式组件

我的投资组合:https://josuenm-portfolio.vercel.app

当我输入页面:

  1. :

几秒钟后的

  1. :

我试着寻找与next.js的样式组件兼容性,但是没有找到任何关于这个bug的东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-29 09:46:30

样式组件是用于客户端呈现的CSS in JS样式解决方案,它通常假设它在浏览器中执行,因此它通过JavaScript执行产生CSS样式,并将它们直接注入文档中。在这种情况下,由于默认情况下Next.js预呈现所有页面,因此需要在服务器端呈现CSS样式,以避免在第一次呈现时出现未样式化的内容。

您可以按照以下步骤这样做:

如果您正在使用Next.js 12+ (与SWC编译器一起使用):

修改next.config.js

代码语言:javascript
复制
/** @type {import('next').NextConfig} */

const nextConfig = {
  // ...rest of options
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

在_document.js文件夹上创建一个自定义的pages文件,并添加:

代码语言:javascript
复制
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    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()
    }
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74242349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档