loading...
Cover image for Use Tailwind CSS 1.1 in your Rails App

Use Tailwind CSS 1.1 in your Rails App

andrewmcodes profile image Andrew Mason Updated on ・4 min read

NOTICE

This tutorial is out of date and may not work for you. I have written a new post based on my experience using Rails and TailwindCSS over the last few months that you can find here. Thanks for reading! 😄

Tutorial

For the purpose of this tutorial, we will assume you have Ruby and the Rails gem installed. Please visit the Getting Started with Rails Guide if you do not.

Create a new Rails project

rails new rails_tailwind --skip-coffee --webpack -d postgresql
cd rails_tailwind
rails db:create
Enter fullscreen mode Exit fullscreen mode

This will create a new Rails project for you with webpack and Postgres configured for you and create our databases. We will not use coffeescript, which is why we add the --skip-coffee flag. You can also omit the -d postgresql flag if you like, but if you want to deploy to something like Heroku, I would recommend adding it. If you keep the Postgres flag, make sure you have Postgres installed and it is running. You can install Postgres on macOS by running brew install postgresql && brew services start postgresql

Running Rails and Webpack

You need to run the Rails server and webpack-dev-server in two terminal tabs/windows unless you use Docker or a gem like Foreman.

For now, we will just create two terminal windows. In one window, run:

rails s
Enter fullscreen mode Exit fullscreen mode

and in the other:

./bin/webpack-dev-server
Enter fullscreen mode Exit fullscreen mode

You should see rails welcome page if you navigate to localhost:3000 in your browser.

rails default information page

Generate a Home controller

In order to see the Tailwind styles that we will integrate later, we at minimum need a controller and view.

rails generate controller Home index
Enter fullscreen mode Exit fullscreen mode

You can remove the generated JS, SCSS, and helper file, we won't be needing them.

rm app/helpers/home_helper.rb app/assets/javascripts/home.js app/assets/stylesheets/home.scss
Enter fullscreen mode Exit fullscreen mode

Configure your routes

Change your config/routes.rb file to:

# frozen_string_literal: true

Rails.application.routes.draw do
  root 'home#index'
  resources :home, only: :index
end
Enter fullscreen mode Exit fullscreen mode

Restart your Rails server, and now you should see the following on localhost:3000

home index

Install Tailwind CSS

Run the following command in your terminal:

yarn add tailwindcss --dev
Enter fullscreen mode Exit fullscreen mode

This should add the Tailwind package to your package.json.

To create a custom config file, you can run:

./node_modules/.bin/tailwind init
Enter fullscreen mode Exit fullscreen mode

This should create a tailwind.config.js file at the root of your project. This file can be used to customize the Tailwind defaults. Read more here

Next, add the following two lines to postcss.config.js

require('tailwindcss'),
require('autoprefixer'),
Enter fullscreen mode Exit fullscreen mode

Your postcss.config.js file should now look like this:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-import'),
    require('tailwindcss'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    })
  ]
}
Enter fullscreen mode Exit fullscreen mode

Configure Tailwind

There are a few ways you can do this but this is my personal preference.

Remove the assets folder:

rm -rf app/assets
Enter fullscreen mode Exit fullscreen mode

Rename the app/javascript directory to app/frontend:

mv app/javascript app/frontend
Enter fullscreen mode Exit fullscreen mode

Tell webpacker to use this new folder by changing the source_path in config/webpacker.yml from: source_path: app/javascript to source_path: app/frontend.

Next, we need to setup our stylesheets:

touch app/frontend/packs/stylesheets.css
Enter fullscreen mode Exit fullscreen mode

Paste the following into our new stylesheets.css file. This is straight from the tailwind docs

@tailwind base;

@tailwind components;

@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Add the following line in app/frontend/packs/application.js:

import './stylesheets.css'
Enter fullscreen mode Exit fullscreen mode

The last step is to tell Rails to use our packs. In app/views/layouts/application.html.erb, change:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
Enter fullscreen mode Exit fullscreen mode

to:

<%= stylesheet_pack_tag 'stylesheets', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
Enter fullscreen mode Exit fullscreen mode

Restart the Rails server and webpack-dev-server and you should now see the following on localhost:3000

tailwind home index

Tailwind should now be working so lets tweak our views to see some Tailwind goodness.

Update views to use TailwindCSS

In app/views/layouts/application.html.erb change:

<body>
  <%= yield %>
</body>
Enter fullscreen mode Exit fullscreen mode

to:

<body class="min-h-screen bg-gray-100">
  <div class="container mx-auto">
    <%= yield %>
  </div>
</body>
Enter fullscreen mode Exit fullscreen mode

and in app/views/home/index.html.erb change:

<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
Enter fullscreen mode Exit fullscreen mode

to:

<section class="py-8 text-center">
  <h1 class="text-5xl mb-2">Ruby on Rails + TailwindCSS</h1>
  <p class="text-xl mb-8">❤️ A match made in heaven️️ ❤️</p>
  <a href="https://tailwindcss.com" class="bg-teal-500 hover:bg-teal-700 text-white font-bold py-4 px-8 rounded" target="_blank">Tailwind Docs</a>
</section>
Enter fullscreen mode Exit fullscreen mode

You should now see the following page when you navigate to localhost:3000

updated tailwind home index

And now you have Tailwind CSS working in your Rails app!

If you are interested in using PurgeCSS to remove unused styles, I recommend checking out GoRails Episode #294

Happy coding!

Discussion

pic
Editor guide
Collapse
abigoroth profile image
Ahmad Ya'kob Ubaidullah

@andew does your @apply feature working on this setup?

Collapse
alvincrespo profile image
Alvin Crespo

Doesn't work for me. Trying with this:

@tailwind base;
@tailwind components;

.field {
  @apply flex flex-col mb-4;
}

@tailwind utilities;

Collapse
andrewmcodes profile image
Andrew Mason Author

I created a new post that should work. Check it out here: dev.to/andrewmcodes/ruby-on-rails-...

Collapse
andrewmcodes profile image
Andrew Mason Author

It was working. Might be time to update this post. I used it today but did something slightly different bc of scss

Collapse
mdahab profile image
Mohammad Dahab

I don't think you should put stylesheets.css inside /packs folder, It will be considered a "pack" and will be compiled to stylesheets-[hash].js.

Collapse
andrewmcodes profile image
Andrew Mason Author

Can you elaborate, please? I do this bc it’s the “rails way” a typically only find pain when I stray from this path. What do you prefer to do?

Collapse
mdahab profile image
Mohammad Dahab

/packs Is a special folder that contains the entry points to your "modules" (webpacker will bundle up each file inside /packs with its dependencies into single file).

So, If you have packs/application.js it will be bundled up with its dependencies and become available as example.com/packs/js/application-[hash].js (Find that in the <head> of your website).

If you check your deployment, you will find example.com/packs/stylesheets-[hash].css which is basically useless because your styles are already bundled to example.com/packs/css/application-[hash].css because of the import './stylesheets.css' you have in app/javascript/packs/application.js already.

Having stylesheets.css inside packs might be just "useless" now. But, It might pile up with time or you might even have your React src folder inside there which basically mean you will have webpacker compiling your app in a loop that might cause 40+ minutes when deploying (I learned the hard way 😅).

Collapse
willjohnsonio profile image
Will Johnson

Is this the way it should be done for Rails versions before 6?

Collapse
mgznv profile image
Collapse
ark profile image
Ark Shraier

Hi, what is your personal experience with Tailwind? What are the key differences from the others

Collapse
andrewmcodes profile image
Andrew Mason Author

Could you describe what you mean by “others”?

Tailwind is not a framework like bootstrap or materialize. It’s a utility framework and best suited for someone who is very comfortable with css, whereas css frameworks provide prebuilt components to get you up and running quickly (in my opinion of course). I love css and tailwind gives me total control + the ability to pull out components like cards. I can move fast, it’s easy to experiment and then pull out reusable components, and it can help you get better at css!