Tailwind and Rails
postcss setup
- tags
- rails
- tailwind
- postcss
Contents
Tailwind is a really nice set of CSS utility classes that let you style up a page staying largely in one file at a time. Rails has it's own wild way of dealing with javascript, so lets go through how to make them play well together.
Install tailwindcss
Make sure that you have node 12.13 or higher:
|
|
If not, then upgrade node.
Inside of your rails project, install tailwind
. We need to use the
PostCSS 7 compatibility build at this time since not all of our
plugins are updated.
|
|
Then we create a directory app/javascript/stylesheets
that we will
have tailwind use. Create a file
app/javascript/stylesheets/application.scss
and import the tailwind
components. If you need to extract and apply different components you
can do it here.
|
|
Finally, we need to add tailwindcss
to the postcss
pipeline. In postcss.config.js
:
|
|
Configuring webpacker
First we need to tell app/javascript/packs/application.js
to use the
new sass sheet:
|
|
And then add the stylesheet_pack_tag
to your layout
In app/views/layouts/application.html.erb
:
|
|
And then update the body
style with a little tailwind goodness, so we can test it out:
|
|
Which we can do by creating a simple route:
|
|
And in config/routes.rb
add a
Which will let you see the generated javascript in real life by starting up rails and going to http://localhost:3000
Setting up production purging
We're going to follow tailwind purgecss directions and create a
tailwind.config.js
file.
|
|
Add in any additional filetypes depending upon which templating system you are using.
Customizing the theme
Tailwind has a lot of ways to change the theme, but lets walk through how to add a different font for the site.
First we'll add a font via npm, from the fontsource project.
|
|
Then, we need to tell webpacker to include it, which is driven off of
app/assets/javascripts/pack/application.js
. Add the required require:
|
|
Then we are need to tell tailwind
to use this new font. First we import the default theme, and then we'll add our new fontFamily
to the front:
|
|
Note that rails is only checking to see if the application.js
file has
changed inside of the app/assets
folder, so if you make a change to
the tailwind.config.js
file you need to touch application.js
to
trigger a rebuild.
Previously
Next