Expo/Next.js自定义字体模块解析失败问题及解决方法
问题解决方法
方法一:使用Google Fonts CDN(亲测有效)
放弃本地字体加载,直接在_document.js的<Head/>中引入Google Fonts的CDN链接,无需额外配置webpack loader,即可在样式中直接使用字体:
<Head> <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet" /> </Head>
之后在CSS中引用字体名称即可:
body { font-family: 'DM Sans', sans-serif; }
方法二:修复本地字体加载配置
如果坚持使用本地字体,可尝试以下调整:
- 调整配置顺序:确保
withFonts包裹withExpo,正确的next.config.js配置应为:
const { withExpo } = require("@expo/next-adapter"); const withFonts = require("next-fonts"); const nextConfig = withFonts(withExpo({ reactStrictMode: true, swcMinify: true, transpilePackages: [ "react-native", "expo", "expo-linear-gradient", "expo-font", "react-native-svg", "lucide-react-native", "prop-types", ], experimental: { forceSwcTransforms: true, }, })); module.exports = nextConfig;
- 检查字体文件:确认
public/fonts/SpaceMono-Regular.ttf路径正确、文件名无大小写错误,且文件本身未损坏。 - 改用Next.js官方字体方案:Next.js 13+内置
next/font,支持本地字体与Google Fonts,无需额外依赖,配置更简单:
// 在页面或组件中引入 import { Space_Mono, Poppins, DM_Sans } from 'next/font/google'; const spaceMono = Space_Mono({ subsets: ['latin'] }); const poppins = Poppins({ weight: ['300', '400', '500', '600', '700'], subsets: ['latin'] }); const dmSans = DM_Sans({ weight: ['400', '500', '700'], subsets: ['latin'] }); // 使用时应用className <div className={spaceMono.className}>Space Mono字体内容</div>
原问题描述
我已按照Expo官方文档配置Next.js项目,当前next.config.js代码如下:
const { withExpo } = require("@expo/next-adapter"); const withFonts = require("next-fonts"); /** @type {import('next').NextConfig} */ const nextConfig = withExpo( { reactStrictMode: true, swcMinify: true, transpilePackages: [ "react-native", "expo", "expo-linear-gradient", "expo-font", "react-native-svg", "lucide-react-native", "prop-types", // Add more React Native / Expo packages here... ], experimental: { forceSwcTransforms: true, }, }, withFonts({ projectRoot: __dirname, }) ); module.exports = nextConfig;
但调试窗口持续出现以下错误:
./public/fonts/SpaceMono-Regular.ttf Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file)
当前依赖项:
"dependencies": { "expo": "^47.0.0", "expo-font": "~11.0.1", "expo-linear-gradient": "~12.0.1", "lucide-react-native": "^0.115.0", "next": "~13.1.1", "next-fonts": "^1.5.1", "prop-types": "^15.8.1", "react": "18.1.0", "react-dom": "18.1.0", "react-native": "0.70.5", "react-native-svg": "13.4.0", "react-native-web": "~0.18.7" },
我目前很喜欢使用Next.js,这是我遇到的第一个问题。我已搜索相关答案但无法复现解决方法。显然问题在于项目无法加载.ttf文件,理论上next-fonts可解决,但我不知道如何正确配置。我尝试过多种配置组合,SpaceMono字体偶尔能成功加载,但换成Poppins或DM Sans等字体时错误立刻出现,不清楚原因。
内容的提问来源于stack exchange,提问作者Stefan Andersen
相关产品推荐
相关产品推荐

