无法在 Create React App 项目中加载自定义字体

Nic*_*ler 5 fonts sass create-react-app

我有一个 create-react-app 项目,使用绝对导入和 css 模块(scss)。我正在尝试定义自定义字体,但导入未得到解决。

尝试了文档中建议的所有内容。

我的文件夹结构

jsconfig.json
public
src
L assets
 L fonts
  L impact.ttf
L index.js
L index.scss
Run Code Online (Sandbox Code Playgroud)

在我的index.scss中

@font-face {
  font-family: 'impact';
  src: url(./assets/fonts/impact.ttf) format('ttf');
}
Run Code Online (Sandbox Code Playgroud)

我的 jsconfig.json (用于绝对导入)

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
Run Code Online (Sandbox Code Playgroud)

import './index.scss'我的 index.js在文件顶部导入。当我尝试编译此代码时,我的组件抛出一个错误,指出无法解析字体文件...

Module not found: Can't resolve './assets/fonts/brush.ttf' in '/Users/xxx/project/src/containers/mycomponent'
Run Code Online (Sandbox Code Playgroud)

还可以使用node-sassscss 文件来工作。这个想不出来了...

Ped*_*nso 5

create-react-app该文件夹位于资产(图像、字体和文件...)的默认文件夹中public

因此,无需创建./src/assets文件夹,只需将“fonts”文件夹移动到“/public”( ./public/fonts)内即可

有关更多信息,请检查: https://create-react-app.dev/docs/adding-images-fonts-and-files/

  • 看起来他们现在建议相反:https://create-react-app.dev/docs/using-the-public-folder (6认同)