首页 > 解决方案 > 将本地字体 .otf 文件导入打字稿项目时找不到模块错误

问题描述

我正在尝试将本地字体导入我的 React/Typescript 项目。

字体文件 ,Averta-Cyrillic_Regular.otf放置在src/assets/fonts/文件夹中。

在同一个fonts.d.ts文件夹中是一个只有一行的文件:

declare module '*.otf'

我的tsconfig.json文件具有以下包含规则:

"include": ["./src/**/*.ts", "./src/**/*.tsx"]

那么从技术上讲,它应该可以正常导入吗?

但是,当我尝试src/assets/fonts/fonts.ts像下面这样导入字体时:

import { createGlobalStyle } from 'styled-components'

import AvertaCyrillicRegular from './Averta-Cyrillic_Regular.otf'

export default createGlobalStyle`
    @font-face {
        font-family: 'Averta Cyrillic Regular';
        src: local('Averta Cyrillic Regular'), local('AvertaCyrillicRegular'),
        url(${AvertaCyrillicRegular}) format('otf'),
        font-weight: 300;
        font-style: normal;
    },
`

它抛出以下错误:

Cannot find module './Averta-Cyrillic_Regular.otf' or its corresponding type declarations.  TS2307

    1 | import { createGlobalStyle } from 'styled-components'
    2 |
  > 3 | import AvertaCyrillicRegular from './Averta-Cyrillic_Regular.otf'

标签: typescriptfonts

解决方案


只需在我们项目的 .d.ts 文件中添加一个带有字体文件扩展名的声明。

declare module "*.woff2"


推荐阅读