Next.js+React环境下Tailwind Typography插件无法生效,标题标签仍显示默认字体样式求助
问题:MDX渲染的标题未应用自定义Tailwind样式
我正在尝试解析MDX文件并将其转换为React组件,技术栈用的是TailwindCSS、Next.js、React。按照Tailwind文档装了@tailwindcss/typography插件,相关配置如下:
tailwind.config.js 插件配置
plugins: [require('@tailwindcss/typography'), require('@tailwindcss/aspect-ratio'), require('tailwindcss-textshadow')]
globals.css 样式配置
@tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply mb-6 text-3xl font-semibold; } h2 { @apply text-2xl font-semibold; } p { @apply mb-4; } a { @apply text-blue-500 hover:text-blue-400 dark:text-blue-400 dark:hover:text-blue-300; } }
Blog组件代码
export const Blog = ({ source, frontMatter }: BlogInput) => { return ( <article className="prose"> <h2>This should have H2 heading style!</h2> <div className={s.title}>{frontMatter.title}</div> <div>{format(parseISO(frontMatter.date!), 'MMMM dd, yyyy')}</div> <div className=""> <MDXRemote {...source} components={components} /> </div> </article> ) }
示例MDX文件内容
--- title: Example Post description: '', date: '2022-01-30' image: '/images/hello.jpg' --- # Heading ### This is an example blog post with React components.
目前遇到的问题是:页面渲染时,标题并未应用自定义的h1/h2字体样式,而是显示Tailwind默认的16px文本,但在VSCode预览插件中可以正常看到样式已生效。请问我是否遗漏了某些配置步骤?
可能的解决方向
1. prose类的样式优先级覆盖了自定义base样式
Tailwind的@tailwindcss/typography插件生成的prose类自带一套完整的文本样式,它给标题元素设置的样式优先级会比你在@layer base里定义的全局h1/h2样式更高,所以你的自定义样式被覆盖了。
你可以试试两种调整方式:
- 给自定义样式加更精准的选择器:把
@layer base里的样式改成针对.prose内部的标题,这样优先级就会超过插件的默认样式:@layer base { .prose h1 { @apply mb-6 text-3xl font-semibold; } .prose h2 { @apply text-2xl font-semibold; } .prose p { @apply mb-4; } .prose a { @apply text-blue-500 hover:text-blue-400 dark:text-blue-400 dark:hover:text-blue-300; } } - 重置
prose的默认标题样式:如果不想用插件自带的标题样式,可以在tailwind.config.js里自定义prose配置,清空它的标题默认样式,这样你的base样式就能生效:module.exports = { theme: { extend: { typography: { DEFAULT: { css: { h1: { fontSize: 'inherit', fontWeight: 'inherit', marginBottom: 'inherit', }, h2: { fontSize: 'inherit', fontWeight: 'inherit', }, // 其他需要重置的标签样式也可以在这里配置 }, }, }, }, }, // 其他原有配置... }
2. MDXRemote渲染的元素需要绑定自定义组件
如果你使用的是next-mdx-remote,MDX里的标题会被渲染成原生h1/h2标签,但如果你的components参数里没有明确指定,可能会有样式继承的问题。你可以手动传入自定义的标题组件,直接带上Tailwind类名:
const components = { h1: ({ children }) => <h1 className="mb-6 text-3xl font-semibold">{children}</h1>, h2: ({ children }) => <h2 className="text-2xl font-semibold">{children}</h2>, // 其他需要自定义的标签也可以在这里添加 }; // 然后在MDXRemote里传入这个components <MDXRemote {...source} components={components} />
这样MDX里的# Heading会直接转换成你定义的带样式的h1组件,样式肯定能生效。
3. 检查Tailwind的内容配置是否包含MDX文件
Tailwind会自动剔除未使用的样式,如果你的MDX文件路径没有被包含在tailwind.config.js的content数组里,它可能会把你定义的h1/h2样式当成未使用的代码删掉。确保你的配置里包含了MDX文件的路径:
module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', './posts/**/*.mdx', // 假设你的MDX文章存在posts目录下 ], // 其他原有配置... }
内容的提问来源于stack exchange,提问作者husky
相关产品推荐
相关产品推荐

