初始加载后 GatsbyJS 未加载 google 字体

GatsbyJS not loading google fonts after initial load

我将 Gatsby 从 v2.x.x 升级到 3,并且像文档中建议的那样,升级了所有 gatsby 插件,包括 gatsby-plugin-styled-components 以及 styled-components

我知道我已经升级了主要版本,这意味着会有重大更改,但我不得不升级 Gatsby,因为它在 M1 macbook 上会损坏。

现在的问题是,我的网站 https://nikhilvijayan.com now doesn't load the google fonts. For eg: the first load works OK (i.e. google fonts load OK), but then clicking on any of the links in the Nav (for eg: https://nikhilvijayan.com/projects) 加载页面时没有任何 google 字体 - 但是,刷新页面后将加载 google 字体。

我最近没有做太多前端工作,想知道是否有人可以指出正确的方向来调试这个问题?这里是否发生了某种竞争条件?

幸运的是,当我在本地 运行 应用程序时也会发生这种情况,所以至少这是一致的行为。

Github 回购:https://github.com/nkhil/portfolio

样式组件使用示例:https://github.com/nkhil/portfolio/blob/main/src/components/Hero.js#L47

这可能不是最佳解决方案,但您可以尝试在 Helmet 组件内的每个页面中导入 google 字体脚本。或者,我会下载字体并在全局 CSS 样式组件中提供它们。

 <Helmet>
    <meta charSet="utf-8" />
    <title>Nikhil Vijayan - Blog</title>
    <meta name="description" content="Blog posts written by 
    Nikhil 
    Vijayan" />
    <link rel="preconnect" href="https://fonts.googleapis.com"/>
    <link rel="preconnect" href="https://fonts.gstatic.com" 
    crossorigin="true"/>
    <link href="https://fonts.googleapis.com/css2? 
     family=Roboto:wght@300&display=swap" rel="stylesheet"/>
  </Helmet>

我认为您的字体在初始渲染时已正确加载,但在每次渲染时都丢失了,因为 @font-face 支持在 styled-components 中非常奇怪 (see GitHub issue)。有很多文章建议使用 font.css 文件。

我建议的解决方案是使用 font.css 文件添加字体,您可以在其中定义 @font-face,直接在 Layout 组件中导入(因为它在您的模板中共享) , 或者使用 Helmet 组件来加载字体,但 仅在 Layout 中,您不需要在所有组件中都使用它,这将导致性能下降。

您甚至可以将这两种方法结合使用:

<Helmet>
  <link rel="stylesheet" type="text/css" href="/fonts.css" />
</Helmet>