How to Setup Tailwind 3 on Rails

1 min read

Update: Tailwind documentation has since added the installation steps with Rails.

Even though the official Tailwind documentation has installation instructions for various client-side frameworks, it is missing one for Rails. Most of the tutorials work with the older versions of Tailwind. With version 3 released a few days ago, I thought it’d be nice to have an up-to-date guide for Rails developers trying to set Tailwind 3 on a Rails app, so here it goes.

Step 1: Install Tailwind CSS

Run the following command from the root directory of your Rails application, which installs the Tailwind package.

npm install -D tailwindcss

Step 2: Initialize Tailwind

By default, Tailwind will look for a tailwind.config.js file at the root of your project where you can define any customizations. The following command generates a tailwind.config.js file in your Rails application.

npx tailwindcss init

Step 3: Configure the source template paths

The content section is where you configure the paths to all of your HTML templates, JS components, and any other files that contain Tailwind class names.

Modify the generated tailwind.config.js file to include all the HTML, JS and ERB files under the app directory.

 module.exports = {
  content: ["./app/**/*.{html,js,erb}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

Step 4: Add Tailwind directives to the CSS

Tailwind is made up of a few different pieces: a reset stylesheet, the utility classes, and functions that make working with Tailwind easier.

In the app/assets/stylesheets/application.css file, add the following Tailwind directives.

@tailwind base;
@tailwind components;
@tailwind utilities;

Step 5: Start the Tailwind CLI build process

Run the following command from the root directory of your Rails application. This will watch for the changes in the view files.

npx tailwindcss -i app/assets/stylesheets/application.css -o app/assets/stylesheets/wind.css --watch

Step 6: Add Tailwind to the HTML

Finally, in the application.html.erb file, add the reference to the generated stylesheet file.

<!DOCTYPE html>
<html>
<head>
  <title>Blog</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag 'wind', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>

That’s it! You have now set up Tailwind in your Ruby on Rails application.