在带有 SCSS 的 Gatsby 站点中,如何导入本地字体?

In a Gatsby site with SCSS how do I import local fonts?

Gatsby 和 SCSS 新手 我想在新的一年开始时深入了解它们。继Gatsby tutorial I wanted to dive in and build a site based off the gatsby-starter.

之后

遵循 install & config for SASS 的文档。

src 中创建了一个名为 fonts 的目录并添加了 Open Sans:

src/fonts/OpenSans-Regular.ttf
src/fonts/OpenSans-Bold.ttf
src/fonts/OpenSans-Italic.ttf

src 中为 SCSS 创建了一个名为 main.scss 的目录,并创建了一个部分目录以引入排版:

src/styles/main.scss
src/styles/partials/_typography.scss

main.scss:

@import 'partials/typography';

body {
  font-family: $font-primary;
}

_typography.scss:

$font-primary: 'Open Sans', sans-serif;

// Body Font:
@font-face {
  font-family: $font-primary;
  font-style: normal;
  font-weight: normal;
  src: url('../../fonts/OpenSans-Regular.ttf') format('truetype');
}

index.js 中,我引入 SCSS 没有任何问题:

import React from 'react'
import '../styles/main.scss'

const Home = () => {
  return <div>Hello world!</div>
}

export default Home

但是在终端中我得到每种字体的字体错误:

Can't resolve '../../fonts/OpenSans-Regular.ttf' in '/path/to/project/src/styles'

If you're trying to use a package make sure that '../../fonts/OpenSans-Regular.ttf' is installed. If you're trying to use a local file make sure that the path is correct. error Generating development JavaScript bundle failed

根据研究,我没有看到答案,我已经阅读:

盖茨比-config.js:

module.exports = {
  plugins: [`gatsby-plugin-sass`],
}

为什么我在尝试为该站点引入本地字体时遇到错误?另外,我正在引入本地字体,因为我在文档中看到了离线能力。


编辑:

使用 Hello World Starter 分叉 Gatsby:

您的心态和方法完全有效,问题取决于您 _typography.scss 中路径的相对性。使用这样的东西:

$font-primary: 'Open Sans', sans-serif;

// Body Font:
@font-face {
  font-family: $font-primary;
  font-style: normal;
  font-weight: normal;
  src: url('../fonts/OpenSans-Regular.ttf') format('truetype');
}

注意错误提示:

Can't resolve '../../fonts/OpenSans-Regular.ttf' in '/path/to/project/src/styles'

/path/to/project/src/styles 很奇怪,由于 /path/to/project/ 部分,您似乎在某处进行了硬编码。也来看看吧。

这个问题取决于你的路径,它是相对于 main.scss 文件的,而不是相对于部分的,因为最终,部分属于 main.scss 文件,因为你正在导入它直接。