DEV Community

Marc
Marc

Posted on • Originally published at webdevchallenges.com

Add Tailwind 2 to Rails 6.1

Originally posted on my blog: https://webdevchallenges.com/add-tailwind-to-rails

How to add Tailwind to Rails 6.1

New Rails Project

rails new myproject
cd myproject
Enter fullscreen mode Exit fullscreen mode

Install dependencies

yarn add tailwindcss@npm:@tailwindcss/postcss7-compat postcss@7 autoprefixer@9
Enter fullscreen mode Exit fullscreen mode

Generate tailwind config

npx tailwindcss init --full
Enter fullscreen mode Exit fullscreen mode

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",
],
Enter fullscreen mode Exit fullscreen mode

Create a scss file for the application

mkdir app/javascript/stylesheets
touch app/javascript/stylesheets/application.scss
Enter fullscreen mode Exit fullscreen mode

Import some basic tailwind stuff in there

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
Enter fullscreen mode Exit fullscreen mode

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

import "stylesheets/application";
Enter fullscreen mode Exit fullscreen mode

Require tailwindcss in postcss

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

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

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' %>
Enter fullscreen mode Exit fullscreen mode

Try it out

Uun the rails server in one terminal

rails s
Enter fullscreen mode Exit fullscreen mode

And the webpack dev server in another one

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

Top comments (0)