TailwindCSS and Rails 8

15 Oct 2024
Security For Rails Developers

Develop the right mindset for Rails security

Avoid shipping vulnerable code by learning how to prevent security issues in your Rails applications.

Get the course for $99

Someone asked on Twitter yesterday about the how to add TailwindCSS to a Rails 8 project the easiest way and having hot reload. This is how I believe it is to do so in a few minutes.

First thing is to add the tailwindcss-rails gem to the project:

bundle add tailwindcss-rails

Then we need to run the installer, to create the Tailwind config files:

rails tailwindcss:install

And now you can run bin/rails tailwindcss:watch to rebuild the CSS files on file changes.

If you use CSS classes in a directory not watched by default, you can add that to config/tailwind.config.js under the content key:

# config/tailwind.config.js
...
content: [
    './public/*.html',
    './app/helpers/**/*.rb',
    './app/javascript/**/*.js',
    './app/views/**/*.{erb,haml,html,slim}',
    './config/**/*.rb',
],
...

And to make your workflow even smoother, you can use Foreman to manage all the necessary processes for you. To set that up is also pretty simple. Create a bin/dev file with the following content:

#!/usr/bin/env sh

if ! gem list foreman -i --silent; then
  echo "Installing foreman..."
  gem install foreman
fi

# Default to port 3000 if not specified
export PORT="${PORT:-3000}"

# Let the debug gem allow remote connections,
# but avoid loading until `debugger` is called
export RUBY_DEBUG_OPEN="true"
export RUBY_DEBUG_LAZY="true"

exec foreman start -f Procfile.dev "$@"

Then create a file named Procfile in the root of your project with the following content:

web: bin/rails server
css: bin/rails tailwindcss:watch

After this, running bin/dev in your terminal will start the Rails server and the Tailwind watcher process.

That’s it. It shouldn’t take more than a few minutes to set this all up.

Or follow me on Twitter

Related posts