Nuxt3中tailwind.config.js无法读取tailwind.css内指定字体的问题求助
解决Nuxt.js 3 + TailwindCSS中自定义字体类不生效的问题
1. 严格匹配字体名称
Tailwind配置里的字体名称必须和@font-face定义的font-family完全一致,包括大小写、空格,这是最容易踩的坑。
比如你的tailwind.css中@font-face定义:
@font-face { font-family: 'Solway'; /* 此处名称要和配置里完全对应 */ src: url('~/assets/fonts/Solway-Regular.ttf') format('truetype'); font-weight: 400; font-style: normal; }
对应tailwind.config.js的配置必须严格匹配:
export default { theme: { extend: { fontFamily: { solway: ['Solway', 'sans-serif'], // 第一个元素必须和@font-face的font-family完全一致 }, }, }, }
2. 确保样式加载顺序与路径正确
在Nuxt3中,把@font-face放入@layer base是正确操作,但要确认样式文件被Nuxt正确导入:
检查nuxt.config.ts配置:
export default defineNuxtConfig({ css: ['~/assets/css/tailwind.css'], // 确认路径无误 modules: ['@nuxtjs/tailwindcss'], })
tailwind.css的标准结构:
@tailwind base; @tailwind components; @tailwind utilities; @layer base { @font-face { font-family: 'Solway'; src: url('~/assets/fonts/Solway-Regular.ttf') format('truetype'); font-weight: 400; font-style: normal; } /* 若有其他字重,需同步引入 */ @font-face { font-family: 'Solway'; src: url('~/assets/fonts/Solway-Bold.ttf') format('truetype'); font-weight: 700; font-style: normal; } }
3. 清除缓存重启服务
Nuxt3的缓存可能导致新配置不生效,执行以下操作:
- 停止当前Nuxt服务
- 删除
.nuxt文件夹和node_modules/.cache文件夹 - 重新运行
npm run dev
4. 验证字体文件路径
确认字体文件路径正确,比如tailwind.css在assets/css/下时,也可以用相对路径:
src: url('../fonts/Solway-Regular.ttf') format('truetype');
测试示例
在组件中使用配置的字体类验证:
<template> <div class="font-solway">测试Solway字体显示</div> <div class="font-solway font-bold">测试Solway加粗字体显示</div> </template>
如果仍不生效,可通过浏览器开发者工具排查:
- 查看元素的
font-family属性是否正确应用Solway - 在Network面板检查字体文件是否加载成功(状态码为200)
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

