无法使用TypeScript导入本地字体

时间:2018-12-12 12:11:38

标签: reactjs typescript webpack

我正在尝试在带有TypeScript项目的React上导入字体文件,但它无法将其识别为字体文件,而是将其视为模块

文件夹结构:

enter image description here

在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(我也尝试过使用file-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'

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

1 个答案:

答案 0 :(得分:3)

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

创建一个DefaultOAuth2AuthorizationRequestResolver文件,并添加以下内容

DefaultServerOAuth2AuthorizationRequestResolver

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

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

确保在fonts.d.ts的{​​{1}}部分中考虑了类型文件。一种很好的方法是在项目中拥有一个根declare module '*.woff'; declare module '*.woff2'; 目录,然后在include上附加tsconfig.json