How to setup TailwindCSS with PayloadCMS and Webpack
Everybody loves TailwindCSS so why not set it up for your React components in Payload? We're going to cover this exact setup with two compile options via the CLI and via a webpack extension.
Setup
Without further hesitation, let's install the dependencies
unknown nodeInitiate your tailwind config file, this function will generate the tailwind.config.js file. In our example we've mapped a custom colour variable to one of Payload's CSS variables, you could do this for all of them so that you have a consistent set of styles in your components.
unknown nodeunknown nodeNow create a tailwind.css file in the root directory so we can use the Tailwind directives
Add our React components
We're going to create a simple React component and inject it to our Payload admin interface so we can test our Tailwind classes in /src/components/NavigationAlert.tsx
This will compile your stylesheet that you can import into your admin panel in /src/css based on your React component. You can add it to a script in your package.json and then run it separately every time
Compile with the CLI
Now you can compile your stylesheet and we're going to do that using the CLI provided by tailwindcss
unknown nodeThis command will compile your stylesheet that you can import into your admin panel in /src/css based on your React component.
You can add it to your package.json scripts so you can run it more easily as well
unknown nodeunknown nodeNow you just need to import the compiled CSS file into your admin
unknown nodeYou should see your component's styles applied.
Compile with Webpack
However, the CLI method isn't the most developer friendly approach as you have to remember to run a separate command. So let's integrate this step directly into our Payload configuration and we'll start by adding our postcss configuration and using those previously installed node modules
Add webpack configuration
We're going to extend Payload's webpack implementation to compile our Tailwind files as well, one thing to note is that the naming of our css rule test is intentionally unique so that it doesn't interfere with Payload's files
unknown nodeAnd now it should automatically compile and work with Tailwind's classes. Here's our ugly NavigationAlert component in action, using Payload's red colour
unknown nodePlease consult the example repository to get a better understanding of how all of this code works together.
Submitted
Attributions