如何将Google字体添加到Gatsby网站

48

开始使用Gatsby - 当我在public/index.html中添加一个带有Google字体的链接标签时,它在开发模式下可以工作。但是当我构建网站时,index.html会被重置。因此,我猜想还有另一种正确的方法来添加字体?

12个回答

52

你也可以使用react-helmet,这在gatsby教程中有讨论。

在头盔组件中包含一个谷歌字体链接元素。

像这样:

<Helmet>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"/>
</Helmet>

我最终选择了这种方式,是因为我已经手动完成了一些样式设置,当我尝试使用排版时,它做出了许多更改,这需要我花费很长时间来撤销。


1
我认为这是最好的解决方案,特别是如果font-face是css框架的依赖项。 - Callat
如果您的项目中已经有了Helmet,那么这就是正确的方法。 - Arno Tenkink

47

例如,在顶部添加以下内容到src/layouts/index.css来导入谷歌的'Roboto'字体

@import url('https://fonts.googleapis.com/css?family=Roboto');

html {
  font-family: 'Roboto', sans-serif;
}

接下来这部分将由 Gatsby 的构建过程处理,并包含在网站的最终生产版本中。


我最终使用了这个。 - dina
8
尽管这种方法有效,但请记住,字体的下载和解析取决于 CSS 解析的完成时间,而 @ptjetty 的回答(在 head 中包含 <link> - 在这种情况下使用 Helmet)是最佳的,因为字体将立即开始下载。 - Estevan Maito

10

我曾经认为 Typefaces 是最佳选择,无需额外的(阻塞)网络请求。

只要你可以在 NPM 上找到你的 字体- typeface


这种方法有什么缺点吗?它似乎是一个真正的“只需运行”解决方案,而且您不需要额外的HTTP请求... - Yann

6
如果您正在结合使用Gatsby和Material UI,以下是最佳方法:
按照Material UI文档中所建议的,在组合使用React Helmet的情况下添加CDN href,以及官方材料UI Gatsby示例中所提供的:Material UI文档他们的GitHub库
创建一个名为RootLayout.jsx的文件(或者根据您的需求进行命名)。
import React from "react";
import { Helmet } from "react-helmet";
import CssBaseline from "@material-ui/core/CssBaseline";

export default function RootLayout({ children }) {
  return (
    <>
      <Helmet>
        <meta
          name="viewport"
          content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
        />
        <link rel="stylesheet"
              href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600&display=swap" />
      </Helmet>
      {children}
    </>
  );
}

将以下代码添加到您的 gatsby-browser.js 中:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

将相同的代码片段添加到您的 gatsby-ssr.js 中:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

解释

布局中的代码通过Gatsby浏览器和SSR API包装了你的React应用程序。这样一来,整个Gatsby应用程序都可以使用该字体。

Gatsby浏览器API链接

Gatsby SSR API链接


4

2
根据Gatsby (React)文档,如果Google字体不以.css结尾,则gatsby-plugin-offline可能会阻止它们在服务器上被请求。我使用了Typography并从CDN导入了一个字体,但后来看到这里的选项可以通过gatsby-config传递以覆盖插件的默认设置。"最初的回答"请参考这里

2

2
您也可以自己托管字体。只需先下载字体文件:https://google-webfonts-helper.herokuapp.com/fonts/,然后将css添加到styles.scss*中:https://google-webfonts-helper.herokuapp.com/fonts/roboto?subsets=latin。在此示例中,src文件夹应如下所示:
/src/
     /styles/style.scss
     /fonts/roboto-v18-latin-regular.eot
     /fonts/roboto-v18-latin-regular.woff2
     /fonts/roboto-v18-latin-regular.woff
     /fonts/roboto-v18-latin-regular.ttf
     /fonts/roboto-v18-latin-regular.svg

* 如果您要使用 SCSS,则需要像这样的插件:https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-sass


1
我喜欢这种方法,只是我在使用文件系统插件时,以便让访问字体文件成为可能。只需确保scss文件中指向字体文件的路径正确无误非常重要:"../fonts/font.ttf"。 - Gerardo Jaramillo

1

现有的答案要么需要手动下载字体(其中一种情况),要么嵌入一个<link>,这将减慢您的网站速度,即使它已经被预取(或者会优化以快速出现,但可能会在下载后通过替换字体来暴露用户到FOUC)。

在2022年,另一种做法是使用fontsource,在这种情况下,gatsby只在构建时下载并合并所需的CSS,而不是在加载时。

请注意,在某些lighthouse报告中(例如gatsby云上的分支预览),与preload标签的比较可能会减慢网站加载速度,但在涉及CDN的生产环境中,自行提供CSS非常快。

以下是我为octue开源主页完整源代码在此处制作两种不同字重的方式。

yarn add @fontsource/open-sans
yarn add @fontsource/work-sans

/*
 * Preload our font CSS at build-time
 * You can do this
 *  - in a theme file (e.g. if using material-ui), or
 *  - in gatsby-browser.js, or
 *  - where the fonts are first used
 */
import '@fontsource/open-sans/400.css'
import '@fontsource/work-sans/300.css'
import '@fontsource/work-sans/400.css'
import '@fontsource/work-sans/500.css'
import '@fontsource/work-sans/500-italic.css'

// The following is not necessary - for example using with MUI only
// If you're using Material-UI or similar, you'll be able to use the font directly
import { createMuiTheme } from '@material-ui/core'

const themeOptions = {
  typography: {
    h1: {
      fontFamily: "'Work Sans', sans-serif",
      fontStyle: 'normal',
      fontSize: '5rem', // Converted from '80px',
      fontWeight: 400,
      lineHeight: '5.5rem', // Converted from '88px',
    },
    body1: {
      fontFamily: "'Open Sans', sans-serif",
      fontWeight: 300, // TODO consider whether to raise to 400 for better aliasing and visibility
      fontSize: '1.125rem', // Converted from 18px
      lineHeight: '1.625rem', // Converted from 26px
      letterSpacing: '0.01rem',
    },
  },
}

  export const theme = createMuiTheme(themeOptions)

这对我来说似乎有效。 - Evan Stern

1

@martis的解决方案非常适用于旧版Gatsby应用程序,但是从gatsby@4.19.0开始,您可以直接使用Gatsby Head API。如链接所示,您需要在页面中导出一个名为Head的函数:

export function Head() {
  return (
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"/>
  )
}

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