如何将谷歌字体添加到盖茨比网站

时间:2017-11-25 16:58:34

标签: reactjs fonts gatsby

Gatsby入门 - 当我使用google字体向public / index.html添加链接标记时,它在开发模式下工作。当我构建网站时,index.html会重置。所以我猜还有另一种正确的方法来添加字体吗?

10 个答案:

答案 0 :(得分:19)

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

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

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

这将由gatsby构建过程处理,并包含在网站的最终生产版本中。

答案 1 :(得分:7)

您还可以使用react-helmet中讨论的gatsby tutorial

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

赞:

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

我最终走了这条路线,因为我已经手动进行了一些样式设置,当我尝试使用Typography时,做了很多更改,这些更改可能需要一段时间才能撤消。

答案 2 :(得分:6)

我的印象是Typefaces是要走的路。没有额外的(阻塞)网络请求。

只要您能在NPM上找到字体 - 字体

答案 3 :(得分:2)

你也可以像在文档中引用的那样使用typography.js:

https://www.gatsbyjs.org/tutorial/part-two/#typographyjs

以下是typeography.js github page,其中列出了目前可用的所有字体组合。

答案 4 :(得分:1)

您也可以自己托管字体。只是

在此示例中,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

答案 5 :(得分:1)

您可以使用此插件https://github.com/escaladesports/gatsby-plugin-prefetch-google-fonts预提取字体,在构建阶段,插件将提取您的字体并将其存储在本地,以便您可以从服务器或CDN提供它们。

答案 6 :(得分:1)

根据Gatsby(react)文档,如果gatsby-plugin-offline不以.css结尾,则gatsby-plugin-offline可能会阻止在服务器上请求Google字体。我使用了Typography,最终从CDN导入了一种字体,但后来看到here这个选项可以传入gatsby-config来覆盖插件的默认设置。

答案 7 :(得分:1)

如果您将Material UI与Gatsby结合使用,这是最佳方法:

按照Material UI documentation中的建议,将CDN href与React Helmet结合使用,并从其github存储库中添加正式的Material UI Gatsby example

创建文件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应用程序中使用。

Link to Gatsby Browser API

Link to Gatsby SSR API

答案 8 :(得分:0)

您可以使用官方 google fonts插件: https://www.npmjs.com/package/gatsby-plugin-google-fonts

答案 9 :(得分:0)

您现在可以npm安装google字体预提取软件包,并将您喜欢的所有字体添加到gatsby-config文件中。然后,像在css文件中一样正常使用字体。在此处签出gatsby文档:https://www.gatsbyjs.com/plugins/gatsby-plugin-prefetch-google-fonts/

相关问题