React无法找到模块-TTF,OTF字体

时间:2019-02-28 10:14:24

标签: javascript css reactjs fonts styled-components

我正在尝试像下面的代码一样加载本地字体,但我不断遇到Cannot find module '@/landing/fonts/Gotham-Bold.ttf'错误,并且不知道此路径的真正错误之处。

我的文件夹结构如下所示,我正在处理的代码为LandingPage.tsx

enter image description here

import { createGlobalStyle } from 'styled-components';
import font from './fonts/Gotham-Bold.ttf'

const Gotham = createGlobalStyle`
  @font-face {
    font-family: 'Gotham';
    font-style: normal;
    font-weight: bold;
    src:
      url(${font}) format('truetype'),
  }
`

2 个答案:

答案 0 :(得分:2)

知道这有点旧,但是Typescript可能有问题。在Typescript中使用字体文件时,必须将格式声明为模块。

为此,您可以创建一个fonts.d.ts文件,并在其中添加以下代码:

declare module '*.ttf';

这样,Typescript将知道如何处理.ttf文件。 您还需要适当的Webpack loader

答案 1 :(得分:0)

根据您的文件夹结构,LandingPages.tsx位于页面文件夹内。 pages文件夹是fonts文件夹的同级文件。您需要从页面文件夹内部遍历到字体文件夹。

正确的路径将是'.././fonts/Gotham-Bold.ttf'

您需要上移(..)一级,然后转到fonts文件夹。

让我知道这是否可以解决您的问题。

相关问题