Gatsby - 将谷歌字体添加到 Gatsby 网站

6

我想在我的Gatsby网站中添加Google字体(Mukta Malar)。

我看到了很多关于如何在Gatsby网站中添加Google字体的文章,大部分似乎都使用这个插件:gatsby-plugin-prefetch-google-fonts

我已经在我的网站中使用了上述插件,只需在gatsby-config.js文件中添加:

plugins: [
    {
      resolve: `gatsby-plugin-prefetch-google-fonts`,
      options: {
        fonts: [
          {
            family: `Mukta Malar`
          },
        ],
      },
    }
  ]

我还将字体族加入了我的 CSS 文件:

* {
  font-family: "Mukta Malar", sans-serif;
}

但是Google字体没有应用到网站上。我的代码中是否有我忽略的隐藏步骤?
3个回答

6

这个插件似乎不再得到维护,并且它是 escalade 的 monorepo 部分(该部分返回 404 错误),核心的最后一次提交是 1 年前。

我建议使用 gatsby-plugin-google-fonts,它允许您在不影响性能的情况下 display: swap 字体。在您的情况下:

{
  resolve: `gatsby-plugin-google-fonts`,
  options: {
    fonts: [
      `mukta malar`
    ],
    display: 'swap'
  }
}

它确实加载了Google字体。但是在默认字体可见时会有一个闪烁的瞬间。有没有一种方法可以预取字体,以便屏幕不会闪烁? - Arunster
这是因为 display: swap。你可以更改这种行为,但这是避免 render-block 的一种方法。字体已经下载,但 CSS 需要被解析,而 display:swap 加载不会阻止 CSS 渲染,当字体被解析时,它就会交换。如果你想避免闪烁,请尝试使用 display: block - Ferran Buireu
1
使用display:block非常顺利。我还学到了font-display的知识。谢谢! - Arunster

4

如其他人所提到的,将字体包含在您的 Gatsby 项目中,这将更快!

Gatsby 实际上在他们的页面上有一个非常好的介绍。

https://www.gatsbyjs.com/docs/how-to/styling/using-web-fonts/

以下是一个示例:

首先,您可以使用 npm 或 yarn 安装字体:

yarn add @fontsource/mukta-malar // npm install 
@fontsource/mukta-malar

然后在页面的布局文件中,按照以下方式导入字体:

import "@fontsource/mukta-malar"

你可以像使用谷歌字体一样在CSS中引用字体:

font-family: 'Mukta Malar', sans-serif;

如果您只需要几个特定的字重或变体,您也可以像这样仅导入软件包的部分内容:
import "@fontsource/mukta-malar/500.css" 
  • 这将仅加载权重为500,也就是“中等”权重。

1
你能否将你的代码格式化为片段,以提高答案的可读性? - Yves Gurcan
抱歉!这样好一些吗?我在StackOverflow上发布还是有点新手。 - Lars Ejaas
1
是的!这样好多了!谢谢你! - Yves Gurcan

3

Google字体可以在npmjs.org上找到,名称为typeface-XXX,其中XXX是Google字体网站上字体系列的名称。

如果我想在我的网站上添加Poppins字体,只需要在package.json文件中添加它:

yarn add typeface-poppins

那么在我的网站中,我可以使用 require("typeface-poppin") 来使用这种字体:

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"


require('typeface-poppins')

const IndexPage = () => (
  <Layout>
    <SEO title="Home" />
    <h1 style={{fontFamily: "Poppins"}}>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
      <Image />
    </div>
    <Link to="/page-2/">Go to page 2</Link> <br />
    <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
  </Layout>
)

export default IndexPage


4
“typefaces” 已经不再使用,现在被“fontsources”所替代:https://github.com/fontsource/fontsource(您可以在“typefaces”网页上找到相关通知):https://github.com/KyleAMathews/typefaces - suther

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