无法使用 TypeScript 导入本地字体 [英] Cannot import local fonts with TypeScript
问题描述
我正在尝试使用 TypeScript 项目在 React 上导入字体文件,但它不会将其识别为字体文件,而是将其视为模块
I am trying to import font files on React with TypeScript project, but it doesn't recognize it as a font file, but instead, it looks at it as a module
文件夹结构:
在我的 index.tsx 文件中,我导入了我需要的字体,并导出了字体常量:
In my index.tsx file, I imported the font I need, and exported Font constant:
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
I use url-loader(I also tried with file-loader). This is my 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]',
},
},
},
这是我得到的错误:找不到模块'./HelveticaNeueW02-45Ligh.woff'
这个问题的原因可能是什么?
What could be the cause of this problem?
推荐答案
您需要将字体文件格式声明为模块,以便 TypeScript 能够正确解析它们.
You need to declare the font file formats as modules so that TypeScript can parse them correctly.
创建一个 fonts.d.ts
文件并添加以下内容
create a fonts.d.ts
file and add the following to it
declare module '*.woff';
declare module '*.woff2';
它告诉 TypeScript 字体文件类型是有效的导入模块.
It tells TypeScript that the font filetypes are valid import modules.
d.ts"文件格式用于提供有关用 JavaScript 编写的 API 或第三方导入的形状的打字稿类型信息.
The "d.ts" file format is used to provide typescript type information about an API that's written in JavaScript, or the shape of the third party imports.
确保在 tsconfig.json
的 include
部分中考虑了类型文件.一个不错的方法是在您的项目中有一个根 typings
目录,然后在 include
上附加 typings/**/*.d.ts
.
Make sure that the types file is considered in the include
section in tsconfig.json
. A nice approach is to have a root typings
directory in your project, then append typings/**/*.d.ts
on include
.
这篇关于无法使用 TypeScript 导入本地字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!