swyxio / swyxdotio

This is the repo for swyx's blog - Blog content is created in github issues, then posted on swyx.io as blog pages! Comment/watch to follow along my blog within GitHub
https://swyx.io
MIT License
325 stars 43 forks source link

How to add Tailwind 3 to Docusaurus 2 in 2022 #456

Closed swyxio closed 1 year ago

swyxio commented 1 year ago

category: tutorial slug: tailwind-docusaurus-2022

We use Docusaurus at work, and while it shipped v2 this year it still has (as of v2.3) not shipped with any Tailwind support at all. Googled and found this post which was almost everything I needed, but required some stuff in the comments for it to work.

Here are the requirements I have, that differed from that blogpost:

just writing down my version that affirmatively worked for me.

Step 1 - install stuff

# in the docusarus directory
yarn add tailwindcss postcss autoprefixer
touch tailwind.config.js # intentionally empty; we'll fill in our own in a bit

Step 2 - Setup tailwind config and css files

// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  corePlugins: {
    preflight: false, // disable Tailwind's reset
  },
  content: ["./src/**/*.{js,jsx,ts,tsx}", "../docs/**/*.mdx"], // my markdown stuff is in ../docs, not /src
  darkMode: ['class', '[data-theme="dark"]'], // hooks into docusaurus' dark mode settigns
  theme: {
    extend: {},
  },
  plugins: [],
}

and also the @tailwind includes:

/* https://dev.to/sajclarke_62/using-tailwindcss-v3-in-docusaurus-in-5-steps-5c26 */
@tailwind base;
@tailwind components;
@tailwind utilities;

// ...

Step 3 - Custom docusaurus plugin

this part is exactly as per the blogpost:

// ...
    plugins:    [
                  // ....
                  async function myPlugin(context, options) {
                    return {
                      name: "docusaurus-tailwindcss",
                      configurePostCss(postcssOptions) {
                        // Appends TailwindCSS and AutoPrefixer.
                        postcssOptions.plugins.push(require("tailwindcss"));
                        postcssOptions.plugins.push(require("autoprefixer"));
                        return postcssOptions;
                      },
                    };
                  },
                ],

and you are done.

to test, convert /docs/whatever.md to /docs/whatever.mdx and insert a React element or component (did you know you can define React components inline in MDX? its weird af, but it works...)

export function Section() {
  return <div className="bg-red-500 dark:bg-yellow-500">this is tailwind!</div>
}

# Welcome to Docs

this works in light and dark mode

<Section />

whoooo it works

Caveats

Because preflight is off, some assumptions break:

chongqiangchen commented 1 year ago

darkMode: ['class', '[data-theme="dark"]'] This doesn't work for me.