Gatsby-将Google字体添加到Gatsby网站

问题描述

我正在尝试在我的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字体不适用于该网站。我的代码中是否缺少隐藏的步骤?

解决方法

此插件似乎已不再维护,它是escalade monorepo(会引发404错误)的一部分,它是1年前在内核中提交的。

我建议您使用gatsby-plugin-google-fontsdisplay: swap字体而不影响性能。就您而言:

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

npmjs.org上提供了Google字体,其名称为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

,

正如其他人提到的,在你的 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 的“中等”重量。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...