It is possible to add tailwind to the Asset Pipeline without using Webpacker, and without tailwindcss-rails either.
If you use the new Tailwind CLI you can build tailwind classes, connect them to the asset pipeline and purge unused classes on the fly.
The general instructions for using the Tailwind CLI are in the installation section which is currently in their docs you will need node installed to have access to the npx command.
Once you understand the general approach use the following steps:
- Update the generated
tailwind.config.js to turn on Just In Time compiling and to configure class purging in rails
module.exports = {
mode: 'jit',
purge: [
'./app/**/*.html.erb',
'./app/helpers/**/*.rb',
'./app/assets/javascripts/**/*.js'
],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {},
plugins: [],
}
Make sure that you add all the path's where you will declare Tailwind classes otherwise purge may remove classes that you are using (read Writing purgeable HTML tailwind docs for more details)
- During development run the watcher process so that your CSS is being continually built based on the HTML you write
npx tailwindcss --no-autoprefixer -o ./vendor/assets/stylesheets/tailwind.css -w
Note that I am placing the generated tailwind styles into vendor/assets but you can place them anywhere the asset pipeline looks for css.
Also, I still use autoprefixer-rails gem so that I can apply the correct prefixes across both tailwind and my project css. In this case you need to set --no-autoprefixer in the tailwind watch command so you are not running it twice.
- Then import the tailwind styles into your
app/assets/stylesheets/application.scss with @import 'tailwind'
Provided the file is in your assets path the styles will be imported.
- Make sure you have a deployment option to re-compile your tailwind.css file as the JIT compilation may is not guaranteed (this is suggested by Tailwind). This will depend on how you deploy but I run the following during deploy:
NODE_ENV=production npx tailwindcss --no-autoprefixer -o ./vendor/assets/stylesheets/tailwind.css
That should be it.
I run this approach with Rails 6.1 but it doesn't use anything special and I expect it should run with Rails 5 projects.
Finally, you may be interested in using the Tailwind @apply feature to set some default styling with Tailwind classes. This is also possible with this setup. To do it you need to have an extra file for the base classes which is used during the Tailwind compilation. The important thing here is not to add this file into your application.scss as the Asset Pipeline will not understand @apply.
I add the few styles that I do to a app/assets/stylesheets/tailwind/base.css file.
I then amend the compilation watcher to npx tailwindcss --no-autoprefixer -i ./app/assets/stylesheets/tailwind/base.css -o ./vendor/assets/stylesheets/tailwind.css -w which will gather all the base styles set and compile them into the tailwind output file.
Good luck with it.