【问题标题】:Cannot import local fonts with TypeScript无法使用 TypeScript 导入本地字体
【发布时间】:2019-05-13 13:01:54
【问题描述】:

我正在尝试在 React with TypeScript 项目中导入字体文件,但它不会将其识别为字体文件,而是将其视为模块

文件夹结构:

在我的 index.tsx 文件中,我导入了我需要的字体,并导出了 Font 常量:

import helveticaNeueLightWoff from './HelveticaNeueW02-45Ligh.woff';
import helveticaNeueLightWoff2 from './HelveticaNeueW02-45Ligh.woff2';
import helveticaNeueMediumWoff from './HelveticaNeueW02-67MdCn.woff';
import helveticaNeueMediumWoff2 from './HelveticaNeueW02-67MdCn.woff2';
import helveticaNeueBoldWoff from './HelveticaNeueW02-75Bold.woff';
import helveticaNeueBoldWoff2 from './HelveticaNeueW02-75Bold.woff2';
import helveticaNeueBoldCnWoff from './HelveticaNeueW02-77BdCn.woff';
import helveticaNeueBoldCnWoff2 from './HelveticaNeueW02-77BdCn.woff2';

const Fonts = {
  helveticaNeueLightWoff,
  helveticaNeueLightWoff2,
  helveticaNeueMediumWoff,
  helveticaNeueMediumWoff2,
  helveticaNeueBoldWoff,
  helveticaNeueBoldWoff2,
  helveticaNeueBoldCnWoff,
  helveticaNeueBoldCnWoff2,
};

export default Fonts;

我使用 url-loader(我也尝试过使用文件加载器)。这是我的 webpack.config.ts

{
          test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
          use: {
            loader: 'url-loader',
            options: {
              // Limit at 50k. Above that it emits separate files
              limit: 50000,
              // url-loader sets mimetype if it's passed.
              // Without this it derives it from the file extension
              mimetype: 'application/font-woff',
              // Output below fonts directory
              name: './fonts/[name].[ext]',
            },
          },
        },

这是我得到的错误:Cannot find module './HelveticaNeueW02-45Ligh.woff'

这个问题的原因可能是什么?

【问题讨论】:

    标签: reactjs typescript webpack


    【解决方案1】:

    您需要将字体文件格式声明为模块,以便 TypeScript 可以正确解析它们。

    创建一个fonts.d.ts 文件并将以下内容添加到其中

    declare module '*.woff';
    declare module '*.woff2';
    

    它告诉 TypeScript 字体文件类型是有效的导入模块。

    “d.ts”文件格式用于提供关于用 JavaScript 编写的 API 或第三方导入的形状的 typescript 类型信息。

    确保在tsconfig.jsoninclude 部分中考虑了类型文件。一个不错的方法是在您的项目中创建一个根 typings 目录,然后在 include 上附加 typings/**/*.d.ts

    【讨论】:

    • 如果我的文件有这样的命名模式怎么办:font.woff?inline?
    • 如果使用tsc,则文件名fonts.ts 中不需要.d。然后编译为fonts.d.ts
    • 很好的答案,谢谢
    【解决方案2】:

    为面临类似问题的 expo 用户完成上一个答案: 我遇到了同样的问题,声明模块足以导入字体,但不能实际加载这些。 我使用的是expo-font,Typescript 抱怨结果的类型。为了使它工作,我创建了具有以下内容的相同文件:

    declare module "*.ttf" {
      const value: import("expo-font").FontSource;
      export default value;
    }
    

    这表明导入的模块将具有来自expo-font 库的FontSource 类型。然后我就可以加载我的字体了:)

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 2020-10-22
      • 2016-06-11
      • 2021-06-16
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多