【问题标题】:In a Gatsby site with SCSS how do I import local fonts?在具有 SCSS 的 Gatsby 站点中,如何导入本地字体?
【发布时间】:2021-04-16 00:31:51
【问题描述】:

对 Gatsby 和 SCSS 不熟悉,我想在新年伊始深入了解这两个方面。在关注Gatsby tutorial 之后,我想潜入并建立一个基于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

但在终端中,每种字体都会出现字体错误:

无法解析“/path/to/project/src/styles”中的“../../fonts/OpenSans-Regular.ttf”

如果您尝试使用软件包,请确保已安装“../../fonts/OpenSans-Regular.ttf”。如果您尝试使用本地文件,请确保路径正确。 错误生成开发 JavaScript 包失败

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

gatsby-config.js:

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

为什么我在尝试为该站点引入本地字体时会出错?另外,我引入本地字体是因为我在文档中看到有离线功能。


编辑:

带有 Hello World Starter 的分叉 Gatsby:

【问题讨论】:

  • 感谢沙盒。我已经更新了修复它的答案。

标签: sass fonts gatsby


【解决方案1】:

您的心态和方法是完全有效的,问题取决于您的_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');
}

注意提示的错误:

无法解析“../../fonts/OpenSans-Regular.ttf” '/path/to/project/src/styles'

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

问题取决于您的路径,它与 main.scss 文件相关,而不是部分,因为最终,部分属于 main.scss 文件,因为您直接导入它。

【讨论】:

  • 啊,我明白了,文档并不清楚路径,但我也认为这意味着任何依赖某些来源的开发部分也需要基于 main.scss 路径的路径,因为它是默认组合所有部分。
  • 如果您通过main.scss 组合部分,可以。如果您在彼此之间导入部分,则不需要,因为您指向特定文件
猜你喜欢
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2021-12-12
  • 2021-05-11
  • 1970-01-01
  • 2021-03-31
相关资源
最近更新 更多