As you know Tailwind is a very popular PostCSS solution. I want to add TailwindCSS in my Angular app running version 11.2.0 or with older versions. How can I do so?
I decided to post and answer my own question because this is a very popular question I have seen through the Angular community recently
Install with npm install -D tailwindcss
Install TailwindCSS plugins(Optional):
npm i @tailwindcss/typography
npm i @tailwindcss/forms
tailwind.config.js
It should look like this:
module.exports = {
prefix: '',
purge: {
content: [
'./src/**/*.{html,ts}',
]
},
darkMode: 'class', // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [require('@tailwindcss/forms'),require('@tailwindcss/typography')],
};
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
if you are using CSS not SCSS, your file should look like this:
@tailwind base;
@tailwind components;
@tailwind utilities;
Go to any of you components and write the following:
<button
class="py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-400">Hello</button>
Now run ng serve
, you should see the following button
If we don't purge, our CSS can be very heavy due to all the CSS classes TailwindCSS adds for you. If you purge, all the unused classes will be removed.
The way I figured to do purging in Angular 11.2.0 are the following ways:
A) This is my preferred way. Add this to your building SCRIPT NODE_ENV=production ng build --prod
and your tailwind.config.js file should look like this.
purge: {
enabled: process.env.NODE_ENV === 'production',
content: [
'./src/**/*.{html,ts}',
]
},
B) In your tailwind.config.js file
you can set the enabled
property inside of the purge
property to true
. This will run purge all the time, be aware of that.
....
prefix: '',
purge: {
enabled: true,
content: [
'./src/**/*.{html,ts}',
]
},
....
Then you can run ng build --prod
and you will see your bundle since getting smaller.
Before purging
After purging
To learn more about Angular (11.2.0 or older version) with TailwindCSS, look at my article
https://dev.to/angular/setup-tailwindcss-in-angular-the-easy-way-1i5l