Getting Tailwind classes when using MDX
Answered
Gouty oak gall posted this in #help-forum
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?11 Replies
Gouty oak gallOP
For reference, here's my
Here's my
Here's my
And finally
mdx-components.tsximport 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.tsimport 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 configHere's my
next.config.jsconst withMDX = require('@next/mdx')()
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
}
module.exports = withMDX(nextConfig)And finally
postcss.config.jsmodule.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
to capture all tsx files inside src
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