【问题标题】:Failed to load font-family downloaded from google fonts in create-react-app project无法在 create-react-app 项目中加载从谷歌字体下载的字体系列
【发布时间】:2021-09-20 11:26:12
【问题描述】:

我已经在我的 create-react-app 项目中下载了谷歌字体。

在 package.json 中

  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "node-sass": "^6.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

在 App.scss 中

@font-face {
    font-family: "Tangerine";
    src: local("Tangerine"), url("/src/assets/fonts/Tangerine/Tangerine-Regular.ttf") format("truetype");
}

@font-face {
    font-family: "Roboto";
    src: local("Roboto"), url("/src/assets/fonts/Roboto/Roboto-Regular.ttf") format("truetype");
}

$font-home-page: "Tangerine", "Roboto";

运行我的应用程序时产生的错误消息

Failed to compile.

./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-6-3!./node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-6-4!./src/App.scss)
Error: Can't resolve './src/assets/fonts/Tangerine/Tangerine-Regular.ttf' in '/Users/.../src'

你知道我遇到了什么问题吗?

【问题讨论】:

    标签: reactjs create-react-app node-sass google-fonts


    【解决方案1】:

    我通过更正 App.scss 中的静态资源路径解决了这个问题。

    现在 App.scss 文件看起来像这样

    @font-face {
        font-family: "Tangerine";
        src: local("Tangerine"), url("../src/assets/fonts/Tangerine/Tangerine-Regular.ttf") format("truetype");
    }
    
    @font-face {
        font-family: "Roboto";
        src: local("Roboto"), url("../src/assets/fonts/Roboto/Roboto-Regular.ttf") format("truetype");
    }
    
    $font-home-page: "Tangerine",
    "Roboto";
    

    只需在 url() 中的路径前加上“..”即可。

    有关 create-react-app 如何加载字体和图像的更多信息 create-react-app docs

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2013-07-16
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2014-10-26
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多