Install Tailwind CSS with PostCSS 7 compatibility
Run the following command to add tailwind to your project and package.json
.
yarn add tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
Create Tailwind Configuration
The following command will create a tailwind.config.js file where you can setup the default configuration for TailwindCSS.
npx tailwindcss init
The Tailwind config file will be empty and should look like this:
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
If you compile all Tailwind CSS classes the generated CSS file will be huge. Let's enable Just-in-time compilation to only extract the classes we use from our views, helpers and javascript files.
module.exports = {
mode: 'jit',
purge: [
'./app/views/**/*.html.erb',
'./app/helpers/**/*.rb',
'./app/javascript/**/*.js',
],
};
Adding Tailwind to PostCSS config
You will need to add the following line to the postcss.config.js file to include it in the compiling process.
require('tailwindcss')('tailwind.js'),
Here is an example of my postcss.config.js file:
module.exports = {
plugins: [
require('tailwindcss')('./app/javascript/css/tailwind.js'),
require('postcss-import'),
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
})
]
}
Import Tailwind to your Javascript Pack
You will need to import tailwind via javascript.
Create an application.css file in app/javascript/css/
I usually keep this in a folder called css, you could choose any other folder that's convenient for you inside the app/javascript directory
Add the following to your application.css file that you just created:
/* tailwind */
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
Import application.css in your app/javascript/packs/application.js file.
import "../layouts/application.css";
Import Tailwind to your layout
Now that you have added TailwindCSS to your application pack, you will have to import it in application.html.erb to use tailwind globally in your application and make it work with Webpack.
Add the following line to app/views/layouts/application.html.erb
in <head>
:
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
And that’s it!
*Instructions based on Bodhish Thomas post and tweaked to my personal usage.
Top comments (1)
Nice article