WebDevChallenges Logo
WebDevChallenges

Add Tailwind 2 to Rails 6.1

Updated June 6, 21
How to add Tailwind 2 to a Rails 6.1 Project including Purging unused rules to improve performance.

How to add Tailwind to Rails 6.1

New Rails Project

rails new myproject
cd myproject

Install dependencies

yarn add tailwindcss@npm:@tailwindcss/postcss7-compat postcss@7 autoprefixer@9

Generate tailwind config

npx tailwindcss init --full

Add purge paths to the newly generated file (tailwind.config.js) to reduce the css file dramatically.

purge: [
  "./app/**/*.html.erb",
  "./app/helpers/**/*.rb",
  "./app/javascript/**/*.js",
  "./app/javascript/**/*.vue",
],

Create a scss file for the application

mkdir app/javascript/stylesheets
touch app/javascript/stylesheets/application.scss

Import some basic tailwind stuff in there

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

Import that file in app/javascript/packs/application.js

import "stylesheets/application";

Require tailwindcss in postcss

Add the following require to the postcss.config.js file

require('tailwindcss'),

Import the tailwind stylesheet pack

Import the stylesheet_pack_tag in your layouts (app/views/layouts/application.html.erb)

<%= stylesheet_pack_tag 'application', media: 'all' %>

Try it out

Uun the rails server in one terminal

rails s

And the webpack dev server in another one

./bin/webpack-dev-server