Configuring tailwindcss for Rails 6 with webpacker

One of the best things about Rails is that it’s an opinionated framework that has a “right” way to do everything already built in. Your application design and style is a differentiator though and is definitely not something your CSS framework (looking at you Bootstrap and Bulma) should be opinionated about. Tailwind is that CSS Framework. Since configuration of Tailwind is different in rails than their installation tutorial I’m going to write how to do it here.

To get started with tailwind install using your package manager of choice

# Using npm
npm install tailwindcss

# Using Yarn
yarn add tailwindcss

In Rails 6 with webpacker, your CSS is packed from ./app/javascript/stylesheets/application.scss

In this file you need to import all the things

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

Don’t worry if your IDE complains about not being able to resolve these, it doesn’t know what it’s talking about.

If this is your first time using that .css file you may also need to update your application layout in app/views/layouts/application.html.erb with the following line

<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

You’ll also need to import the new application.css file in app/javascript/packs/application.js

import '../stylesheets/application.css'

That’s all you need to be able to start adding Tailwind defined CSS classes to your HTML. If you also want to be able to configure those CSS classes, you’ll need generate a tailwind config js file

npx tailwindcss init

This will place a tailwind.config.js file in the root of your application directory. For Rails, we need this file to be packed as well so it should be moved somewhere inside your ./app/javascript folder. ./app/javascript/tailwind.config.js is fine for this example. Once it’s there, you’ll need to tell webpacker about it in ./postcss.config.js by adding the following plugins.

require('tailwindcss')('./app/javascript/tailwind.config.js'),
require('autoprefixer')

Make sure the path matches where you placed the config file and you should be good to go. If you update the config file in dev it will be repacked on the next page reload.

I recommend testing the config file to ensure that it works. Add something like

module.exports = {
theme: {
maxWidth: {
'1/4': '25%'
}
},
variants: {},
plugins: [],
}

And test it out in your HTML

<p class="max-w-1/4">Hello Tailwind!</p>

Happy styling!