Each time I go to startup a new Rails app for a side project I can’t remember how to set tailwind up correctly and end up looking through 3 or 4 different approaches until I find one that looks "correct".
With cssbundling-rails, this is now a thing of the past. The new (css|js)bundling-rails gems are super thin wrappers around setting up your own build task in package.json, and all it has to do is dump a file into app/assets/builds
to be included via the asset pipeline.
What’s even handier though is tailwind is included out of the box using the new JIT mode.
Installation
All you have to do is add gem 'cssbundling-rails'
to your Gemfile and then run
rails css:install:tailwind
After that, you will have a build:css
script added to your package.json and a new binstub to run your Rails app alongside the tailwind JIT.
# Now you run rails with:
bin/dev
Extra credit: Using @imports with postcss
This is completely optional, but I have a few apps where I needed to write additional styles or wrap some tailwind components up using tailwinds @apply helper, so there’s a little extra step to get this working.
You need to add --postcss
to your build:css
script, so it will look something like:
{
"scripts": {
"build:css": "tailwindcss --postcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css"
}
}
After that install a few dependencies:
yarn add postcss postcss-flexbugs-fixes postcss-import postcss-nested postcss-preset-env
And finally create a postcss.config.js
in the root of your Rails app.
module.exports = {
plugins: [
require("autoprefixer"),
require("postcss-import"),
require("tailwindcss"),
require("postcss-nested"),
require("postcss-flexbugs-fixes"),
require("postcss-preset-env")({
autoprefixer: {
flexbox: "no-2009",
},
stage: 3,
}),
],
};
Now you can create components in app/assets/stylesheets/components/*.css
and @import
them in your main application.tailwind.css file.
Note: you may need to change the tailwind imports to use post css like so:
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
Top comments (5)
Looking forward to ripping webpack out of some major projects - need a quiet week or two planned to take that leap though! At least getting Postcss8, Tailwind2 + JIT running has become easier recently
I hope this helps you get set up with Rails and tailwind that little bit easier. These new approaches to assets are going to ship with Rails 7 and replace webpacker, which I think is great and a much more Rails like way of doing things.
Hey!
thanks for sharing. I am confused as to whether I should use css-bundling or is tailwindcss-rails, any thoughts on how both compare?
How do I add tailwind plugins?
Hey Timur, the same way you would normally, installing via cssbundler-rails will generate a
tailwind.config.js
in your project, so yarn install the plugin and then add it to your config.Hope that helps!