Setup Webpacker Tailwindcss - Paprikas/rails_cheat_sheet GitHub Wiki

Tailwind CSS 2+ works well with the latest Webpacker (beta 7 at the moment)

Add webpacker gem

gem "webpacker", "6.0.0.beta.7"

Run install

bundle exec rails webpacker:install

Make sure you have a strict version in package.json

"@rails/webpacker": "6.0.0-beta.7",

You can rename paths in config/webpacker.yml if you wish

  source_path: app/javascript
  source_entry_path: packs

Add webpack-dev-server to your Procfile if you use foreman for dev

webpack: bin/webpack-dev-server

Update your config/initializers/content_security_policy.rb

  Rails.application.config.content_security_policy do |policy|
    policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development?
  end

Setup webpacker-dev-server host ENV variable if you use docker

WEBPACKER_DEV_SERVER_HOST=your-app-service-in-docker

Add ports in your docker-compose

version: "3.8"
services:
  web:
    ports:
      - 3035:3035

To enable css support

yarn add css-loader mini-css-extract-plugin css-minimizer-webpack-plugin
// config/webpack/base.js
const { webpackConfig, merge } = require('@rails/webpacker')
const customConfig = {
  resolve: {
    extensions: ['.css']
  }
}

module.exports = merge(webpackConfig, customConfig)

Tailwind CSS

Installation Guide

Add packages

yarn add tailwindcss@latest postcss@latest autoprefixer@latest postcss-import@latest

Create postcss.config.js

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Generate Tailwind CSS config file

npx tailwindcss init

Replace with these values (don't forget to revise them)

module.exports = {
  purge: {
    enabled: ["production", "staging"].includes(process.env.NODE_ENV),
    content: [
      './**/*.html.erb',
      './app/helpers/**/*.rb',
      './app/javascript/**/*.js',
    ],
  },
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Update postcss.config.js

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

Enable JIT

module.exports = {
  mode: 'jit',
  purge: {
    enabled: ["production", "staging"].includes(process.env.NODE_ENV),
    content: [
      './**/*.html.erb',
      './app/helpers/**/*.rb',
      './app/javascript/**/*.js',
    ],
  },
  darkMode: 'media', // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

TLDR

sass sass-loader postcss-loader

Troubleshooting

If you have issues with undefined merge, add this to your config/webpack/base.js

const { merge } = require('webpack-merge');