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

React+Vite项目中@font-face引入字体失败问题求助

问题:React + Vite + Sass 引入@font-face字体解析错误

我使用React + Vite结合Sass开发应用,在通过@font-face引入字体时遇到异常:Chrome中字体能正常显示但抛出解析错误,Firefox中字体完全无法加载。


相关代码文件

_fonts.scss

@font-face {
      font-display: swap;
      font-family: 'Monoton';
      font-style: normal;
      font-weight: 400;
      src: url('../assets/fonts/monoton-v19-latin-regular.woff2'),
           url('../assets/fonts/monoton-v19-latin-regular.ttf');
    }

_variables.scss

@import 'fonts';

$font-family-heading: 'Monoton', sans-serif;
$font-size-heading: 24px;

App.module.scss

@import '../../sassStyles/variables';

.heading {
  font-family: $font-family-heading;
  font-size: 120px;
}

错误信息

Chrome报错内容

Failed to decode downloaded font: http://localhost:5173/assets/fonts/monoton-v19-latin-regular.woff2
localhost/:1 OTS parsing error: invalid sfntVersion: 1008821359
localhost/:1 Failed to decode downloaded font: http://localhost:5173/assets/fonts/monoton-v19-latin-regular.ttf
localhost/:1 OTS parsing error: invalid sfntVersion: 1008821359

Firefox报错内容

downloadable font: rejected by sanitizer (font-family: "Monoton" style:normal weight:400 stretch:100 src index:1) source: http://localhost:5173/assets/fonts/monoton-v19-latin-regular.ttf 

解决方法

  1. 检查字体文件完整性
    invalid sfntVersion错误说明字体文件可能损坏或格式不兼容。重新从官方渠道下载Monoton字体,替换现有文件,确保下载过程无中断。

  2. 添加字体格式声明
    在@font-face的src项中补充format属性,帮助浏览器识别字体类型:

    @font-face {
      font-display: swap;
      font-family: 'Monoton';
      font-style: normal;
      font-weight: 400;
      src: url('../assets/fonts/monoton-v19-latin-regular.woff2') format('woff2'),
           url('../assets/fonts/monoton-v19-latin-regular.ttf') format('truetype');
    }
    
  3. 配置Vite资源规则
    在vite.config.js中显式声明字体文件类型,确保Vite正确处理:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    export default defineConfig({
      plugins: [react()],
      assetsInclude: ['**/*.woff', '**/*.woff2', '**/*.ttf', '**/*.otf']
    })
    
  4. 使用绝对路径别名
    配置Vite路径别名避免相对路径出错:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import path from 'path'
    
    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          '@assets': path.resolve(__dirname, 'src/assets')
        }
      },
      assetsInclude: ['**/*.woff', '**/*.woff2', '**/*.ttf', '**/*.otf']
    })
    

    随后在_fonts.scss中使用别名路径:

    src: url('@assets/fonts/monoton-v19-latin-regular.woff2') format('woff2'),
         url('@assets/fonts/monoton-v19-latin-regular.ttf') format('truetype');
    
  5. 清理缓存重启服务
    清空浏览器缓存,删除Vite的node_modules/.vite缓存目录,再重启开发服务。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:12:45