[Rails] Setup TailwindCSS via Webpacker

October 18, 2020

Introduction

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

Definition from TailwindCSS website.

With Boring Generator

Boring Generator installation guide.

> rails generate boring:tailwind:install
> rails generate boring:tailwind:install --skip_tailwind_css_ui
> rails generate boring:tailwind:install --skip_tailwind_css_ui --skip_tailwind_init_full
OPTIONS:
  skip_tailwind_css_ui:    Skip adding @tailwindcss/ui package
  skip_tailwind_init_full: Skip running tailwindcss init with --full option

Without Boring Generator

1. Add Tailwind CSS via NPM packages

  yarn add @tailwindcss/ui

Add @tailwindcss/ui package to use the Tailwind UI components.

  yarn add @tailwindcss/ui

2. Initialize the Tailwind configuration.

yarn tailwindcss init
OR
yarn tailwindcss init --full

--full adds all the Tailwind configuration used internally in the config generated and allows you to override them directly in the configuration.

3. Add Tailwind to PostCSS config

// postcss.config.js

module.exports = {
  plugins: [
    // ...
    require('tailwindcss'),
    require('autoprefixer'),
    // ...
  ]
}

4. Add and compile Tailwind CSS via Webpack

// app/javascript/stylesheets/application.scss

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

5. Require Stylesheet

Require the stylesheet in the application.js to be available in the entire application. Rails 6 by default adds the javascript_pack_tag in the application.html.erb to apply all the JS via webpack on the entire application. Please make sure you have javascript_pack_tag added in your application layout.

// app/javascript/packs/application.js

import "stylesheets/application"

Happy Coding!!!