For a new project I finally got a chance to explore Tailwind CSS
. A utility-first CSS
framework you’ve most likely heard of before.
Tailwind is build on top of the vast JavaScript tooling that is flourishing around Node.js. We are lucky to have support for that in Rails since the introduction of webpack in Rails 5.1.
I tried to find the smallest amount of steps needed to get Tailwind working in a fresh, yet deployable Rails 6 application. Tailwind generates a bazillion CSS classes, so clearing out all the unused ones is a must-do for production deployments and therefore included in the following steps via PurgeCSS.
Installing the needed tools
The following creates a new rails application with webpack included by default. I’m choosing PostgreSQL as database to allow deployments to Heroku right away. But feel free to pick something else.
$ rails new freshwind -d postgresql
$ cd freshwind
$ yarn add tailwindcss --dev
$ yarn add @fullhuman/postcss-purgecss --dev
I’m providing a Git patch at the end of this article you can apply
right after rails new ...
.
PostCSS Configuration
From here on I’m basically following the
official installation guide
adjusted to Rails. PurgeCSS is only run on production builds. I’m still using
regular Rails views in ./app/views/**/*.html.erb
. Extend the content
array
with more paths for React, Vue, etc.
// postcss.config.js
const purgecss = require('@fullhuman/postcss-purgecss')({
// Specify the paths to all of the template files in your project
content: [
'./app/views/**/*.html.erb'
],
// Include any special characters you're using in this regular expression
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})
module.exports = {
plugins: [
require('postcss-import'),
require('postcss-flexbugs-fixes'),
require('tailwindcss')('./app/javascript/css/tailwind.js'),
require('autoprefixer'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}),
...process.env.NODE_ENV === 'production'
? [purgecss]
: []
]
}
Starting to use TailwindCSS
At this point TailwindCSS is installed. Let’s adjust the default Rails layout
to start making use of it. In development stylesheet_pack_tag
will return nil
while all your CSS is delivered through the JS pack. You can control this with
extract_css
in webpacker.yml
.
<!-- app/views/layouts/application.html.erb -->
<!-- ... -->
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- ... -->
/* app/javascript/css/application.css */
/* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */
@tailwind utilities;
// app/javascript/packs/application.js
// ...
import '../css/application.css'
Deployment to Heroku
Allow Heroku to make use of modules in devDependencies
:
$ heroku config:set NPM_CONFIG_PRODUCTION=false
Git Patch
Apply everything mentioned here via patch file.