Recently, I needed to get Tailwind CSS running on a new Rails 8 app. Here’s how I got everything set up!
1. Create Your Rails App
Start by creating a new Rails app using the rails new
command:
rails new tailwindcss_demo
Rails provides a shortcut by allowing you to pass the --css=tailwind
option to rails new
, which automatically sets up Tailwind. However, in my case, I already had a working Rails app and needed to add Tailwind manually. That’s what I’ll focus on here.
2. Install the Required Gems
The tailwindcss-rails gem provides all the necessary tooling to integrate Tailwind into a Rails app. Add it to your Gemfile
and run bundle install
:
# Gemfile
gem "tailwindcss-rails"
bundle install
3. Run the Tailwind Install Task
Next, run the Tailwind install task to set up the necessary files:
bin/rails tailwindcss:install
This command generates several files, including:
Tailwind Stylesheet
In app/assets/stylesheets/application.tailwind.css
, you'll find the main Tailwind CSS file where you can add your styles:
@tailwind base;
@tailwind components;
@tailwind utilities;
/*
@layer components {
.btn-primary {
@apply py-2 px-4 bg-blue-200;
}
}
*/
Tailwind Configuration
The install script also generates a Tailwind configuration file at config/tailwind.config.js
:
const defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
content: [
'./public/*.html',
'./app/helpers/**/*.rb',
'./app/javascript/**/*.js',
'./app/views/**/*.{erb,haml,html,slim}'
],
theme: {
extend: {
fontFamily: {
sans: ['Inter var', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [
// require('@tailwindcss/forms'),
// require('@tailwindcss/typography'),
// require('@tailwindcss/container-queries'),
]
};
4. Running Tailwind in Development
The installation process also sets up a tailwind:watch
task. This process runs alongside your Rails server and automatically rebuilds your frontend assets when changes are detected.
To start your Rails app with Tailwind watching for changes, use:
foreman start
The Tailwind install script will have added this process to your Procfile
, ensuring that both your Rails server and the tailwind:watch
task run together.
Conclusion
Setting up Tailwind CSS in a Rails app is straightforward, thanks to the tailwindcss-rails
gem. If you're creating a new app, you can simplify the process by using rails new myapp --css=tailwind
, which takes care of everything out of the box. However, if you’re adding Tailwind to an existing app, the steps above will get you up and running quickly!
Top comments (0)