javascript - React 找不到模块 - ttf、otf 字体

标签 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'),
  }
`

最佳答案

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

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

declare module '*.ttf';

这样 Typescript 就会知道如何处理 .ttf 文件。 您还需要一个合适的 Webpack loader .

关于javascript - React 找不到模块 - ttf、otf 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54923215/

相关文章:

html - 如何在区域上显示多个div并合理填充

javascript - React 中的函数声明 'this' 范围

javascript - 使用 BootstrapDialog.show 时禁用外部点击

javascript - 如何修复“未定义”错误的 "Uncaught TypeError: Cannot read property ' 滚动高度'

javascript - React-Native:虽然前面有声明,但 undefined 不是对象

javascript - 垂直居中 div 溢出

Javascript : how to insert tags around a text selection?

javascript - addClass 到当前 li 元素并 removeClass

reactjs - React 路由器重定向条件

javascript - React Js 单击时反向反转数组