Why use PostCSS?
The default and the easiest way to use Tailwind CSS with Rails is to use the --css=tailwind
flag of the rails new
command.
This will install the tailwindcss-rails gem which wraps a standalone executable
version of Tailwind CSS.
This is great for getting started, but has some limitations:
- You can't easily import CSS from other packages and include them in your build
- You can't use SASS or PostCSS nesting easily
- There aren't any build hooks allowing you to do more complex builds
How
The next logical step from using the tailwindcss-rails gem is to use PostCSS instead. This is easy to setup with Rails and is well supported by Tailwind.
Using PostCSS with Rails uses esbuild to build the CSS. This also has the benefits of giving you a full build pipeline for your JavaScript, should you have more sophisticated needs there as well.
Setup
Create your app using the following command which creates a new Rails app with PostCSS and esbuild:
rails new example_base3 -c postcss
Install Tailwind CSS with yarn:
yarn add tailwindcss @tailwindcss/forms @tailwindcss/aspect-ratio @tailwindcss/typography @tailwindcss/container-queries
Generate a Tailwind config file with the following command:
yarn run tailwind init
Then customise tailwind.config.js
using the full code example below, and add Tailwind to the PostCSS build by adding require('tailwindcss')
to the postcss.config.js
file.
Finally you can get the project started by running bin/dev
. This will start the Rails server and the esbuild watcher (defined as build:css
in package.json
).