You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS服务下使用@font-face时浏览器无法获取woff字体文件求助

NestJS 字体静态资源加载异常解决方案

两类异常的核心原因是 NestJS 默认没有对外暴露静态资源目录,你存放字体的fonts目录未完成服务端路由映射,导致客户端请求无法定位到对应文件。


步骤1:注册静态资源目录

首先根据你使用的服务适配器,完成fonts目录的路由映射配置:

1.1 Express 适配器(NestJS 默认适配器)

先安装静态资源服务依赖:

npm install @nestjs/serve-static

在app.module.ts中注册目录映射:

import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      // 填写fonts目录的物理存储路径
      rootPath: join(__dirname, '..', 'fonts'),
      // 配置对外访问的路由前缀
      serveRoot: '/fonts',
    }),
  ],
})
export class AppModule {}

1.2 Fastify 适配器

先安装Fastify静态资源依赖:

npm install @fastify/static

在main.ts中注册目录映射:

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );
  app.register(require('@fastify/static'), {
    root: join(__dirname, '..', 'fonts'),
    prefix: '/fonts/',
  });
  await app.listen(3000);
}
bootstrap();

步骤2:修正@font-face路径配置

使用绝对路径配置字体地址,避免页面路由层级变化导致的相对路径解析错误:

@font-face {
  font-family: Roboto;
  src: url(/fonts/roboto-v29-latin-regular.woff);
}

异常问题排查

如果配置后仍有问题,检查以下两点:

  • 确认fonts目录会被拷贝到编译后的dist目录中,TypeScript项目默认不会打包非TS后缀文件,需要在nest-cli.json中配置资源拷贝规则:
    {
      "compilerOptions": {
        "assets": ["fonts/**/*"]
      }
    }
    
  • 确认全局拦截器、守卫没有拦截静态资源的GET请求,避免返回默认空对象响应。

内容的提问来源于stack exchange,提问作者tomwe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:45:03