使用Emotion和Gatsby时出现的未样式化内容闪烁问题(FOUC)?

4

我正在尝试为一个已存在的Gatsby静态网站添加Emotion。总体来说,效果非常好,但是服务器渲染实际上并没有渲染样式。加载后的短暂时刻或者如果您禁用了JavaScript则永久性地只能看到一个全局样式的.js文件。

我尝试了 https://www.gatsbyjs.org/docs/troubleshooting-common-errors 中关于清除缓存、确保模块安装以及升级软件包版本至最新版本的步骤。没有运气。

这是否是一个已知的问题,可以解决?

您可以在 https://github.com/JoshuaKGoldberg/Goldblog/tree/945d0ca8501b3aa069ef44145e4d05daa35da505 上查看完整的存储库。

1个回答

3
你正在使用@emotion/core,它使用css属性,但你将你的样式令牌传递给了className属性。如果你使用的是需要额外设置才能使服务器端渲染工作的emotion包,则应该这样做。请参阅文档中的此页面进行比较和更多细节说明
解决方法是首先移除你的css()函数调用,然后在你的样式对象文字周围添加css` `模板字符串。
// replace this
export const header = css({
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "row",
    flexWrap: "wrap",
    marginTop: "1.5rem",
});

// with this
export const header = {
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  flexDirection: "row",
  flexWrap: "wrap",
  marginTop: "1.5rem",
}

然后,无论您在何处传递要使用Emotion处理的对象或数组,都将className替换为css

// replace this
<header className={styles.header}>
  <h1 className={styles.heading}>
    <Link className={styles.headingLink} to={`/`}>
      {title}
    </Link>
  </h1>
  <Bio />
</header>

// with this
<header css={styles.header}>
  <h1 css={styles.heading}>
    <Link css={styles.headingLink} to={`/`}>
      {title}
    </Link>
  </h1>
  <Bio />
</header>

完美,这正是我所需要的。谢谢! - Josh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接