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

导入TTF字体文件触发SyntaxError: Invalid or unexpected token错误求助

解决React-PDF导入TTF字体的SyntaxError问题

你的推测完全正确——Node.js/ts-node会把TTF文件当作JS代码解析,而二进制字体内容不符合JS语法,所以抛出了SyntaxError。以下是几种可行的解决配置方案:

方案一:直接读取字体文件(最简便,适合Node.js环境)

放弃import方式,用Node.js的fs模块直接读取字体文件为Buffer,react-pdf支持直接传入Buffer作为字体源:

import { Font } from '@react-pdf/renderer';
import fs from 'fs';
import path from 'path';

// 读取字体文件为Buffer
const fontBuffer = fs.readFileSync(path.join(__dirname, './NotoSansJP-Regular.ttf'));

Font.register({
  family: "NotoSansJP-Regular",
  format: "truetype",
  src: fontBuffer,
});

方案二:配置ts-node处理TTF文件

如果坚持要用import语法,需要给Node.js添加自定义扩展名处理器,让它正确读取TTF二进制内容:

  1. 创建register-ttf.js文件:
const fs = require('fs');

// 注册.ttf文件的处理逻辑,返回文件Buffer
require.extensions['.ttf'] = function(module, filename) {
  const content = fs.readFileSync(filename);
  module.exports = content;
};
  1. 修改启动脚本(package.json),先加载这个处理器:
"scripts": {
  "start": "node -r ./register-ttf.js -r ts-node/register src/你的入口文件.ts"
}
  1. 完善d.ts类型声明(可选,增强类型提示):
declare module '*.ttf' {
  const content: Buffer;
  export default content;
}

方案三:TypeScript资源配置(适用于ES模块环境)

如果你的项目使用ES模块(tsconfig中module设为ESNext/Node16),可以在tsconfig.json中添加资源包含规则,同时确保使用支持资源加载的工具链:

{
  "compilerOptions": {
    "module": "Node16",
    "moduleResolution": "Node16",
    "esModuleInterop": true,
    "assetsInclude": ["**/*.ttf"]
  }
}

注意:这种方式需要配合支持资源加载的构建工具(如Vite、Webpack),纯ts-node环境可能仍需方案二的处理器配合。

内容的提问来源于stack exchange,提问作者The Blind Hawk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:55:28