Tailwind CSS移除Remark/Rehype生成页面样式的问题及解决咨询
问题概述
我有一个Next.js项目,近期添加了Tailwind CSS用于样式设计,但它完全破坏了通过Remark和Rehype创建的部分博客文章页面格式。问题在于Tailwind的Preflight会重置默认样式,我在博客中使用的<p>、<h1>、<h2>、<ul>和<ol>元素都受到了影响。
我的实现方式
我用于将Markdown转换为HTML的代码如下:
import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; import { unified } from 'unified'; import remarkParse from 'remark-parse'; import remarkGfm from 'remark-gfm'; import remarkRehype from 'remark-rehype'; import rehypeRaw from 'rehype-raw'; import rehypeStringify from 'rehype-stringify'; import rehypeAttr from 'rehype-attr'; const postsDirectory = path.join(process.cwd(), 'posts'); export async function getPostData(id) { const fullPath = path.join(postsDirectory, `${id}.md`); const fileContents = fs.readFileSync(fullPath, 'utf8'); // Use gray-matter to parse the post metadata section const matterResult = matter(fileContents); // Use remark to convert markdown into HTML string and rehype to add HTML format. const processedContent = await unified() .use(remarkParse) .use(remarkGfm) .use(remarkRehype, { allowDangerousHtml: true }) .use(rehypeRaw) .use(rehypeAttr, { p: { className: 'text-gray-700 my-10' }, h1: { className: 'text-3xl font-bold' }, }) .use(rehypeStringify) .processSync(matterResult.content); const contentHtml = processedContent.toString(); // Combine the data with the id and contentHtml return { id, contentHtml, ...matterResult.data, }; }
当前问题出在
processedContent变量的声明部分。
我原本希望通过rehype-attr库为上述元素添加样式,但在上述示例中(仅编辑<p>和<h1>元素)没有效果。我还了解到rehype-add-classes库,但它会给程序注入漏洞,因此我不愿使用。
我的想法
我认为最佳解决方案是使用类似rehype-attr的工具为指定HTML元素添加className;如果此方法不可行,我也愿意在这些页面上停用Tailwind CSS。但后者的问题在于,我已按照文档说明将Tailwind直接添加到globals.css文件中,并在_app.js中全局应用。
内容的提问来源于stack exchange,提问作者Ramon Orraca
相关产品推荐
相关产品推荐

