Ramon Orraca
Ramon Orraca

Reputation: 111

Tailwind CSS is unstyling page created through remark and rehype

Problem overview

I have a Next.js project in which Tailwind was recently added for styling purposes, and it completely destroyed the format of some blog post pages created through Remark and Rehype. The problem is that Tailwind CSS removes styling from <p>, <h1>, <h2>, <ul>, and <ol> components which I use in the blog post.

My implementation

The code I use to convert Mardown into HTML is the following:

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,
  };
}

The current problem is inside the processedContent variable declaration.

Through the rehype-attr library I was hoping to be able to style things in the aforementioned components, but in the example shown above (editing only <p> and <h1> elements) this had no effect. I also read about this library called rehype-add-classes, but the code injects some vulnerabilities into my program so I'd rather not use this.

An example of the website working without Tailwind (and the style working correctly) can be found here and the same website with the Tailwind implementation breaking things can be found here.

What I'm Thinking

I think the best solution would be using something as rehype-attr to add any given className to the desired HTML elements, but if this is not possible I would also be happy to deactivate Tailwind CSS from this pages. The problem with the later solution is that I added Tailwind directly into the globals.css file as instructed in their docs and then used this inside _app.js to apply this on every page.

Upvotes: 2

Views: 979

Answers (0)

Related Questions