DEV Community

Cover image for Setup TailwindCSS in Angular the easy way
Pato for Angular

Posted on • Updated on

Setup TailwindCSS in Angular the easy way

In this tutorial, I'm going to show you how to integrate TailwindCSS to your Angular project the EZ EZ way.

This tutorial is for people that want to work with TailwindCSS in their Angular application with the new released version 11.2.0 (comes with native support for TailwindCSS now 😉) or with with older versions.

YOU CAN SKIP THE 💩 AND GO STRAIGHT TO THE INSTALLATION STEPS

Content

  • What is TailwindCSS?
  • How does TailwindCSS work?
  • Advantages of TailwindCSS
  • Disadvantages of TailwindCSS
  • Installing TailwindCSS (Angular version < 11.2.0)
  • Installing TailwindCSS (Angular version >= 11.2.0)
  • Making sure TailwindCSS is working in Angular
  • Purge Tailwind in Angular prod build

What is TailwindCSS?

"A utility-first CSS framework packed with classes like flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup." - Tailwind team

How does TailwindCSS work?

TailwindCSS is different than other CSS frameworks like Bootstrap. It comes with a set of utility classes(CSS classes). This will allow you to create and combine the classes to give your UI the aspect that you want. TailwindCSS allows you to customize their styles in a very easy way to create your own design systems.

Advantages of TailwindCSS

  • You will spend more time in your business logic rather than your CSS
  • Pre-made utility classes ready to use
  • You add their classes like you would with any CSS class
  • Light weight in production
  • Mobile first
  • Expandable and customizable
  • Use it the "old school" way by applying their styles into your CSS classes
  • Extensions for your IDE
  • Well documented
  • Well supported by different tools like Vue and React
  • You can always inspect the TailwindCSS classes in a website and see the actual CSS code :)
  • The naming convention for the classes make sense e.g space-y-4 it will add a vertical(Y-AXIS) space of 4 pixels between your HTML elements.

Disadvantages of TailwindCSS

  • I don't recommend it if you are new to CSS, not because is hard but because it makes you lazier. You won't be writing any CSS sometimes just adding classes
  • Can make your HTML very dirty. If you add a lot of classes to you HTML element it can get ugly, quick! A solution for this is to create components using the classes from TailwindCSS that way you clean up your HTML

Installing TailwindCSS (Angular version < 11.2.0)

If your Angular version is greater than or equal to 11.2.0, you can skip this section

The easiest way to use TailwindCSS in your Angular app with version less than 11.2.0 in my personal opinion is by using the @ngneat/tailwind npm package. I had a great experience with it (plug and play).

  1. First step is to run the following schematic in your Angular project: ng add @ngneat/tailwind

  2. When asked if you want to enable dark mode select class

  3. When asked if you would you like to use Tailwind directives & functions in component styles? select Yes

  4. When asked what TailwindCSS plugins you want to enable, select forms and typography or all of them. That's up to you.

angular tailwind

There's 4 parts we need to focus on after we have installed TailwindCSS in our Angular app.

-A new file created tailwind.config.js it should look like this
-A new file created webpack.config.js it should look like this
-The new dark class added to your index.html body element

<body class="dark">
  <app-root></app-root>
</body>
Enter fullscreen mode Exit fullscreen mode

-Some imports added to your styles.scss file

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
Enter fullscreen mode Exit fullscreen mode

Note: To turn on purge in your production build follow this tiny tweet

OPTIONAL

Take a look to this amazing video created by my friend Beeman. It shows you how use TailwindCSS in Angular in 3 MINUTES!

Installing TailwindCSS (Angular version >= 11.2.0)

If your Angular version is less than 11.2.0, you can skip this section and look at the instructions above for installation. If you already performed the previous steps, go to Testing TailwindCSS in Angular section below.

  1. Install with npm install -D tailwindcss

  2. Install TailwindCSS plugins(Optional):

Some people are running older versions of the CLI or the @angular-devkit/build-angular. Make sure your package.json looks AT LEAST with version 11.2.0this or have a more recent versions (if available)

  1. Create a TailwindCSS configuration file in the workspace or project root. Name that configuration file 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')],
};
Enter fullscreen mode Exit fullscreen mode
  1. In your styles.scss file add the following TailwindCSS imports
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
Enter fullscreen mode Exit fullscreen mode

if you are using CSS not SCSS, your file should look like this:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Making sure TailwindCSS is working in Angular

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>
Enter fullscreen mode Exit fullscreen mode

Now run ng serve, you should see the following button

angular tailwindcss

If you don't want to have that many classes in your HTML, you can clean it up by putting the TailwindCSS classes in your CSS/SCSS files.

.btn {
    @apply py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-400
}
Enter fullscreen mode Exit fullscreen mode

** Notice I'm using the @apply **

<button class="btn">Hello</button>
Enter fullscreen mode Exit fullscreen mode

Github Repo of project running Angular 11.2.0 and Tailwind

How to purge TailwindCSS in Production

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}',
      ]
    },
...
Enter fullscreen mode Exit fullscreen mode

B) In your tailwind.config.js file you can set the enabled property inside of the purge property to true

....
prefix: '',
    purge: {
      enabled: true,
      content: [
        './src/**/*.{html,ts}',
      ]
    },
....
Enter fullscreen mode Exit fullscreen mode

Then you can run ng build --prod and you will see your bundle since getting smaller.

Before purging
tailwindcss purging

After purging
purging tailwind

Special thanks to:

Contributors of the ngneat/tailwind package:
Chau Tran
Beeman

and the other contributors of this awesome package.

Special thanks to Kevin, GDE from Angular Taiwan for helping me debug my issues.
Kevin

Special thanks to Vlad, he showed me the purge trick :)
Vlad Tansky

Latest comments (35)

Collapse
 
initvik profile image
Vikas

Please add the postcss configuration in the article seems like its missing

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mafer23 profile image
Maria Fernanda Palencia

thakns and you

Collapse
 
rahiyansafz profile image
Rahiyan Safin • Edited

Could anyone help me out? i made an custom css dark toggle mode theme.
and i want to make it with the tailwind.

stackblitz.com/edit/angular-ivy-b9...

we know that the root of the angular project is app component, so i made like this in the custom css project,

  <a>NIGHT</a>
  <a>DAYa&gt;
</a>
Enter fullscreen mode Exit fullscreen mode

and app component ts:

isDarkEnable = false;
presentTheme$ = new BehaviorSubject('theme-light');

constructor() {}

ngOnInit() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
this.presentTheme$.next(savedTheme);
}
}

changeTheme() {
this.presentTheme$.value === 'theme-light'
? this.presentTheme$.next('theme-dark')
: this.presentTheme$.next('theme-light');
localStorage.setItem('theme', this.presentTheme$.value);
this.isDarkEnable = !this.isDarkEnable;
}

and the global scss is:

.theme-light {
--primary: #2577c1;
--secondary-bg: #fff;
--theme: #fff;
--header-color: rgb(194, 63, 226);
--route-link-active: #fff;
--link-color: rgb(85, 80, 80);
--border-color: rgb(85, 80, 80);
}

.theme-dark {
--primary: rgb(255, 80, 11);
--secondary-bg: #424242;
--theme: #424242;
--header-color: var(--theme);
--route-link-active: rgb(255, 80, 11);
--link-color: #fff;
--border-color: rgb(28, 214, 28);
}

now could anyone help me how to modify it in the tailwind?

Collapse
 
kristher1619 profile image
Kristher Vidal • Edited

Thank you for this wonderful tutorial. I tried this using default setup and it is working.

However when tried it using multiple application setup but it doesn't work when I apply the tailwind classes directly in the html files. Although it does work when using @apply in the scss. files

This does not work

<div class="tw-font-bold">
Enter fullscreen mode Exit fullscreen mode

This work

div {
   @apply tw-font-bold;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devpato profile image
Pato

you mean a monorepo?

Collapse
 
kristher1619 profile image
Kristher Vidal

Yes. 1 Angular Workspace with multiple projects.

Thread Thread
 
kristher1619 profile image
Kristher Vidal

Finally got it to working..

First I enabled purge mode while on develop environment. Also I am linking to the wrong directories.

So for monorepo with multiple projects, purge directory should point inside the projects directory

....
 purge: { enabled: true, content: ["./projects/admin/src/**/*.html", "./projects/admin/src/**/*.ts"] },
....
Enter fullscreen mode Exit fullscreen mode


`

Collapse
 
johanchouquet profile image
Johan CHOUQUET

Hi there,

Thanks a lot for this.

As you probably know, in sass, the @import syntax is not the recommended way of importing. We should use @use instead.
So, what about changing those @import to @use ? Would that still work as expected ?

Collapse
 
ahmedayman0 profile image
Ahmed Ayman Elkemary

Shouldn't we build css to make tailwind directive @apply work properly?

Collapse
 
brandonpittman profile image
Brandon Pittman

space-y-4 === 1rem not 4px

Collapse
 
devpato profile image
Pato

Thank you

Collapse
 
psycomentis06 profile image
Amor Ali

Easy and simple tutorial, and I spent 7 hours to make it works!!. You may be wondering why ? I cloned the GitHub repo serve it and I had the same error. Because I'm using Node 10 while Tailwind v2 dropped Node 10 support. So if you have node v10 update it to 12 at least and things will work smoothly.
Please put notice to help people from spending their time trying to do this.

Collapse
 
dylut2000 profile image
Hardy Lutula

wow.. thanks alot
this is really helpful

Collapse
 
misticwonder profile image
Andrey Korovin

I would recommend this approach github.com/mw-angular/toolbox/tree...
It is very useful when you need to use tailwind in library (i.e. design-system)

Collapse
 
julgon2012 profile image
Julio 👹

Seguí todos tus pasos en un proyecto totalmente nuevo, de angular 11.2.0 y no funciona.
Además en este código plugins: [require('@tailwindcss/forms'),require('@tailwindcss/typography')],

hay 2 componentes que instalar y tú no lo dices.

Como te dijera en twitter, tu tutorial confunde más de lo que ayuda.

Collapse
 
devpato profile image
Pato • Edited

Hola Julio!

-Ya agregue mas pasos para que no te confundas Julio. Gracias por el feedback!

Saludos!

Collapse
 
1antares1 profile image
1antares1

How would you resolve this error with SCSS Files?
dev-to-uploads.s3.amazonaws.com/i/...

Collapse
 
devpato profile image
Pato • Edited

That's more of a linter issue since it's not used to this type of Syxtax. If I find a way to resolve it I will let you know BUT this shouldn't affect if your app works or not

Collapse
 
pelx profile image
Laura

it does. an app doesn't work!

Thread Thread
 
devpato profile image
Pato

Can you send me a link to your code? mine is working perfectly fine. Also, see the github repo link I posted at the end of the tutorial

Thread Thread
 
pelx profile image
Laura

I added this:
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

.nav-bar {
@apply border-t block no-underline hover:underline py-2 text-grey-darkest hover:text-black md:border-none md:p-0;
}

to my styles.scss file. It will not compile. If I add teh same classes to HTML, it works fine.

ERROR::
Error: ./src/styles.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
SyntaxError

(7:4) C:\dev_dev\tailwind-app\styles.scss The text-grey-darkest class does not exist. If you're sure that text-grey-darkest exists, make sure that any @import statements are being properly processed before Tailwind CSS sees your CSS, as @apply can only be used for classes in the same CSS tree.

cheers
Laura

Thread Thread
 
devpato profile image
Pato

Interesting can you post your tailwind.config.js or send me a link to your repo? I would love to help :)

Thread Thread
 
pelx profile image
Laura

Hi Pato, this is very kind. I have created a repo: github.com/pelx/tailwindcss-app
It actually works, the only problem i still cant nail is linting. I created stylelint.config.js Didn't work. cheers. Laura

Collapse
 
1antares1 profile image
1antares1

Do you understand that for Ionic 5 the installation would be the same?
I follow this tutorial but it seems somewhat extensive...

blog.andrewbrey.com/2020-07-06-usi...

Collapse
 
devpato profile image
Pato

I have not tried it. If you follow mine that is shorter let me know if it works with Ionic. I will credit you on the article

Collapse
 
1antares1 profile image
1antares1

Yes it worked for me, but partially. For example, I had to do the imports from the file global.scss

/* Tailwind files */
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
Enter fullscreen mode Exit fullscreen mode

And in the file tailwind.config.js, add the following colors in the property theme, being this way:

    theme: {
        extend: {},
        colors: {
            primary: {
                default: 'var(--ion-color-primary)',
                shade: 'var(--ion-color-primary-shade)',
                tint: 'var(--ion-color-primary-tint)',
            },
            secondary: {
                default: 'var(--ion-color-secondary)',
                shade: 'var(--ion-color-secondary-shade)',
                tint: 'var(--ion-color-secondary-tint)',
            },
            tertiary: {
                default: 'var(--ion-color-tertiary)',
                shade: 'var(--ion-color-tertiary-shade)',
                tint: 'var(--ion-color-tertiary-tint)',
            },
            light: {
                default: 'var(--ion-color-light)',
                shade: 'var(--ion-color-light-shade)',
                tint: 'var(--ion-color-light-tint)',
            },
            medium: {
                default: 'var(--ion-color-medium)',
                shade: 'var(--ion-color-medium-shade)',
                tint: 'var(--ion-color-medium-tint)',
            },
            dark: {
                default: 'var(--ion-color-dark)',
                shade: 'var(--ion-color-dark-shade)',
                tint: 'var(--ion-color-dark-tint)',
            },
            success: {
                default: 'var(--ion-color-success)',
                shade: 'var(--ion-color-success-shade)',
                tint: 'var(--ion-color-success-tint)',
            },
            warning: {
                default: 'var(--ion-color-warning)',
                shade: 'var(--ion-color-warning-shade)',
                tint: 'var(--ion-color-warning-tint)',
            },
            danger: {
                default: 'var(--ion-color-danger)',
                shade: 'var(--ion-color-danger-shade)',
                tint: 'var(--ion-color-danger-tint)',
            },
            step: {
                '50': 'var(--ion-color-step-50)',
                '100': 'var(--ion-color-step-100)',
                '150': 'var(--ion-color-step-150)',
                '200': 'var(--ion-color-step-200)',
                '250': 'var(--ion-color-step-250)',
                '300': 'var(--ion-color-step-300)',
                '350': 'var(--ion-color-step-350)',
                '400': 'var(--ion-color-step-400)',
                '450': 'var(--ion-color-step-450)',
                '500': 'var(--ion-color-step-500)',
                '550': 'var(--ion-color-step-550)',
                '600': 'var(--ion-color-step-600)',
                '650': 'var(--ion-color-step-650)',
                '700': 'var(--ion-color-step-700)',
                '750': 'var(--ion-color-step-750)',
                '800': 'var(--ion-color-step-800)',
                '850': 'var(--ion-color-step-850)',
                '900': 'var(--ion-color-step-900)',
                '950': 'var(--ion-color-step-950)',
            },
        },
    },...
Enter fullscreen mode Exit fullscreen mode

What remains for me is to be able to compile the CSS so that only the classes used use me, for now the utilities are imported completely :/

But it is an advance hehe!

If you want to see the complete code with Tailwind integrated in Angular 11.2 + Ionic 5, here is a baseline maintained by the Ionic Dominicana community 🥰:
🔗github.com/ionic-dominicana/ionic-...

Thank you for this article, dear.

Collapse
 
peyman98 profile image
Peyman

Thanks, what about purging unused classes? is it done automatically?

Collapse
 
devpato profile image
Pato

I have updated the post with some purging instructions

Collapse
 
chandlerbaskins profile image
Chandler Baskins • Edited

I don't believe its done for you but in your tailwind config file this may work...

purge: {
      content: [
        './src/**/*.{html,ts}',
      ]
    },
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devpato profile image
Pato

Did you see the updated section?

Thread Thread
 
chandlerbaskins profile image
Chandler Baskins

Nice! Thank you for the content ❤️

Thread Thread
 
devpato profile image
Pato

You are welcome sir!

Collapse
 
devpato profile image
Pato • Edited

I updated the tutorial with a purging section :) let me know if you think this sucks or it's good lol

Collapse
 
yannic_420 profile image
Yannic Ellhotka

Thanks for the tutorial.
The only way I could get purging to work was to set the env variable "NODE_ENV" to "production". Does the CLI have the ability to do this automatically when a prodction build is generated?

Collapse
 
devpato profile image
Pato

Hi! Check out this thread let me know if it helps you

twitter.com/mgechev/status/1359892...