Geek Culture
Published in

Geek Culture

Setting Up Rails 6.1 + Tailwind CSS 2.2 with JIT

Ruby on Rails & Tailwind CSS

I’m going to show you how to create a project with Rails 6.1 and its default Webpacker version (4.5), and configure Tailwind CSS with its dependencies and JIT mode enabled.

You’ll end up with a project that compiles the final CSS automatically, and refreshes the browser for you as well, after every change.

Create a Rails application:

Install the Tailwind CSS dependencies. Open the terminal and run:

Create the file app/javascript/stylesheets/application.scss (you will have to create the stylesheets directory).

Now open application.scss and add the Tailwind CSS directives:

Remember that this is an SCSS file, so you can add here the SCSS code you need later.

Open app/javascript/packs/application.js and add this import to include the new application.scss:

Put that line below the last import (channels).

Open postcss.config.js and add this require at the beginning of the plugins array, just before the first require:

Open app/views/layouts/application.html.erb and add this before stylesheet_link_tag:

So it will look like this:

Now you can create the Tailwind CSS configuration file in the terminal:

Enable JIT mode and configure the purge option so that it looks like this:

To prevent Webpacker from generating a rather annoying warning message, open babel.config.js and add this at the bottom, just before the closing ].filter(Boolean):

Remember to add a comma to the previous element. It will look like this:

Finally, to get Webpacker 5 to work with PostCSS 8 we need to add a small hack. Open config/webpack/environment.js and add this before module.exports = environment:

That’s it!

If you want to test if it works, create a test controller:rails g controller Home index

Add the root in config/routes.rb:

Open app/views/home/index.html.erb and create an H1 like this:

Now open the Webpacker server in a terminal tab:

And the Rails server in another tab:

Open your browser and load localhost:3000

You should see a big, red Hello World!

Try making changes, and you’ll see how fast it compiles and refreshes the browser.

As an additional note, for the Tailwind CSS IntelliSense extension to work in html.erb files you must open the preferences and look for the files.associations option. Click the Add Item button and add *.html.erb as item, and html as value.

If you liked the article, and don’t have time to research and study the framework, I recommend my Tailwind CSS course on Udemy, where I explain, to the point, how to use the framework.

I also teach you how to use the 4 official plugins, saving you a lot of work.

Enjoy!

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store