Using Tailwind CSS with Gatsby.js
I'm beginning to rebuild my personal website using Gatsby.js, and of course I want to use my favorite CSS framework, Tailwind CSS! I searched around for a guide on how to use Gatsby and Tailwind together, and couldn't find anything with a full solution, so I decided to write this article as The Definitive Guide™ for how to set up Tailwind with Gatsby 😄.
FYI: If you follow this guide, hot reloading will still work and you'll also get reloading when you change your Tailwind configuration file!
gatsby-plugin-postcssis a Gatsby plugin that allows you to use PostCSS features in CSS files that you import into pages/components. Tailwind is built on PostCSS, so this is a great starting point!
To install the plugin, use your favorite package manager.
Install gatsby-plugin-postcss via NPM or Yarn
Now that we've installed a plugin, we need to configure Gatsby to use it!
Open up your gatsby-config.js, and add
gatsby-plugin-postcssto the plugins array.
Our PostCSS plugin is installed, and Gatsby is using it, so all that's left is to configure the PostCSS side of things! To configure PostCSS, create an empty postcss.config.js file in your project's root (the same folder as the gatsby-config.js file).
Now before we configure PostCSS to use Tailwind, we need to install it.
Install tailwindcss via NPM or Yarn
To configure Tailwind, we'll need to add a Tailwind configuration file. Luckily, Tailwind has a built-in script to do this. Just run the following command (again, in your project's root directory).
This will create a tailwind.js file containing Tailwind's default configuration.
Okay, we've installed and configured Tailwind, now back to our PostCSS config. We need to add Tailwind to PostCSS's list of plugins.
In the example above, you'll see we're passing in a file path. That is the path to our configuration file. So if you'd like to move or rename the Tailwind configuration file, just remember to change the file path in your postcss.config.js file.
Note: You can add any other PostCSS plugins that you'd like to use, like autoprefixer, before or after Tailwind in the array of plugins.
Everything should be ready to go, all we need to do now is to actually use Tailwind within our CSS! First, create a
global.cssfile. I put mine at
src/css/global.css. Then, add the following Tailwind directives to your new file:
For this step, I opted to create a new global.css file, but you could just as easily put the Tailwind directives in an existing CSS file.
The last thing we need to do is to import our new CSS file into a page or layout so that our Tailwind CSS is actually injected into our pages. In
layout.js, or wherever you want your Tailwind CSS to appear, add the following import:
You're done! That's it, you should have a fully functional Tailwind + Gatsby setup, with Tailwind configuration, and Hot Reloading!