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

Vite + React项目中字体无法加载的问题求助

React项目从CRA迁移到Vite后字体加载失败

问题详情

将React项目从Create React App(CRA)切换到Vite构建后,字体完全无法加载,浏览器返回404错误:

GET http://localhost:5173/assets/fonts/Roboto-Regular.woff
[HTTP/1.1 404 Not Found 1ms]

downloadable font: download failed (font-family: "Roboto" style:normal weight:400 stretch:100 src index:0): status=2147746065 source: http://localhost:5173/assets/fonts/Roboto-Regular.woff

当前字体规则文件(src/styles/partials/_fonts.scss):

// _fonts.scss
@font-face {
  font-family: "Roboto";
  src: url("../../assets/fonts/Roboto-Regular.woff") format("woff");
  font-weight: 400;
}

全局样式文件(index.scss):

@use "./styles/partials/fonts" as *;

body {
  font-family: "Roboto", Arial, Helvetica, sans-serif;
}

已排查文件夹结构未发现异常,但相同配置在CRA项目中可正常运行,无法理解Vite开发环境下字体加载失败的原因。

项目文件夹结构:
项目文件夹结构

修复方案

Vite与CRA的资源路径解析逻辑不同,可通过以下方式解决:

  1. 修正字体引用路径
    Vite支持从项目根目录出发的绝对路径,直接使用根目录路径引用字体文件,避免相对路径出错:
// _fonts.scss
@font-face {
  font-family: "Roboto";
  src: url("/src/assets/fonts/Roboto-Regular.woff") format("woff");
  font-weight: 400;
}

如果坚持使用相对路径,需确保路径指向正确的文件位置,可通过查看Vite开发服务器的资源列表验证。

  1. 配置Vite识别字体文件
    Vite默认可能未将woff等字体后缀纳入资源处理范围,在vite.config.js中添加配置:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  assetsInclude: ['**/*.woff', '**/*.woff2']
});
  1. 检查文件名与路径大小写
    Vite开发环境对文件名大小写敏感,而CRA通常不敏感。确认字体文件名(如Roboto-Regular.woff)与引用中的名称完全一致,路径层级也无大小写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:12:16