Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 无法使用TypeScript导入本地字体_Reactjs_Typescript_Webpack - Fatal编程技术网

Reactjs 无法使用TypeScript导入本地字体

Reactjs 无法使用TypeScript导入本地字体,reactjs,typescript,webpack,Reactjs,Typescript,Webpack,我试图在React with TypeScript项目上导入字体文件,但它没有将其识别为字体文件,而是将其视为一个模块 文件夹结构: 在index.tsx文件中,我导入了所需的字体,并导出了字体常量: import helveticaNeueLightWoff from './HelveticaNeueW02-45Ligh.woff'; import helveticaNeueLightWoff2 from './HelveticaNeueW02-45Ligh.woff2'; import h

我试图在React with TypeScript项目上导入字体文件,但它没有将其识别为字体文件,而是将其视为一个模块

文件夹结构:

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

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加载器(我也尝试使用文件加载器)。这是我的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]',
            },
          },
        },
这是我得到的错误:
找不到模块'/helveticaneuw02-45Ligh.woff'


此问题的原因可能是什么?

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

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

declare module '*.woff';
declare module '*.woff2';
它告诉TypeScript字体文件类型是有效的导入模块

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


确保在
tsconfig.json
中的
include
部分中考虑了类型文件。一个很好的方法是在项目中有一个根
typings
目录,然后在
include
上附加
typings/***.d.ts
如果我的文件有这样的命名模式怎么办:
font.woff?inline
?如果使用
tsc
,则不需要在文件名
font.ts
中添加
.d
。然后将其编译为
font.d.ts