Next.js Discord

Discord Forum

Getting Tailwind classes when using MDX

Answered
Gouty oak gall posted this in #help-forum
Open in Discord
Gouty oak gallOP
Hi, I'm using MDX in a project with Next.js 14 and Tailwind, and the styling isn't working as it should be. I think this is because I'm applying Tailwind classes in mdx-components.tsx and the generated result isn't getting picked up by Tailwind. Is there a way to make Tailwind see what classes are used when generating content from an MDX file?
Answered by joulev
add src/mdx-components.tsx to the content array above
View full answer

11 Replies

Gouty oak gallOP
For reference, here's my mdx-components.tsx

import type { MDXComponents } from 'mdx/types'

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    h1: ({ children }) => (
      <h1 className="mb-6 text-2xl font-bold">{children}</h1>
    ),
    h2: ({ children }) => (
      <h2 className="mb-4 text-xl font-bold">{children}</h2>
    ),
    ul: ({ children }) => <ul className="mb-4 list-disc">{children}</ul>,
    p: ({ children }) => <p className="mb-4">{children}</p>,
    ...components,
  }
}


Here's my tailwind.config.ts

import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    screens: {
      mobile: '375px',
      tablet: '768px',
      desktop: '1440px',
    },
    extend: {
      colors: {
        green: '#0ca346',
      },
    },
  },
  plugins: [],
}

export default config


Here's my next.config.js

const withMDX = require('@next/mdx')()

/** @type {import('next').NextConfig} */
const nextConfig = {
  pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
}

module.exports = withMDX(nextConfig)


And finally postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
what's the path to mdx-components.tsx
Gouty oak gallOP
Some classes (like mb-4) which are used elsewhere in my app are having an effect, while others (like mb-6) which are only used in the mdx-components.tsx are not. Ideally it would be nice to have Tailwind classes applied to the generated HTML instead of having to do this manually
@joulev what's the path to mdx-components.tsx
Gouty oak gallOP
It's in the project root
@Gouty oak gall It's in the project root
add src/mdx-components.tsx to the content array above
Answer
in tailwind config
or just do
content: ['./src/**/*.tsx'],

to capture all tsx files inside src
Gouty oak gallOP
Got it, that makes sense. For some reason I was thinking mdx-components.tsx was it's own special case
It works
Might be helpful to add a note about that in https://nextjs.org/docs/app/building-your-application/configuring/mdx since it's a little bit subtle and Tailwind can come bundled with Next. I can open a PR if there's any interest in that
yes that's a good idea, please make a PR