Integrating Tailwind v4 to Docusaurus v3

I will be using shadcn for my application. So, I had to bring in tailwind to docusaurus. Most of the solutions from the web are Tailwind v3 compatible. I tried to use Google Gemini as well, initially it shared the results for tailwind v3 which I had to polish by prompts for correcting it.
To validate the changes mentioned, add the following to any mdx file visible to you.
<div className="tw:text-red-500 tw:dark:text-yellow-500 tw:font-bold p-4">
This text is styled with Tailwind!
</div>
Follow the steps to integrate tailwind to your docusaurus project:
- Install the required dependencies.
yarn add postcss tailwindcss @tailwindcss/postcss autoprefixer
note
Make sure tailwindcss and @tailwindcss/postcss have same versions
- Add the plugin [line 9-17] in the config to plugins property of config object as shown below.
[project_root]/docusaurus.config.ts
import type { Config } from '@docusaurus/types';
const config:Config = {
...
...
plugins: [
...
...
async function tailwindcssPlugin(context, options) {
return {
name: "tailwindcss-plugin",
configurePostCss(postcssOptions) {
postcssOptions.plugins.push(require("@tailwindcss/postcss"))
return postcssOptions
},
}
},
],
...
...
}
- Add the following css code to
src/css/custom.cssto make tailwindcss available to the application. If you have not gone through the official documentation you might find the below CSS strange. In the following css we are skipping the preflight css added by@import "tailiwindcss"which overwrites the css of docusaurus default classic theme. For more details, please refer to preflight config in tailwind v4.
src/css/custom.css
@layer theme, base, components, utilities;
@import "tailwindcss/theme.css" layer(theme) prefix(tw);
@import "tailwindcss/utilities.css" layer(utilities) prefix(tw);
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
note
Adding prefix(tw) is optional, I did this to avoid any surprising conflict in future.