DEV Community

Árni Gunnarsson
Árni Gunnarsson

Posted on

Adding Tailwindcss to an Angular 11.2+ project

Angular CLI recently, as of version 11.2, added out of the box support for Tailwindcss. Adding Tailwindcss used to be quite hard but is now a breeze and it is an absolute pleasure to work with Tailwindcss.

Adding the necessary packages and basic setup

npm install tailwindcss postcss autoprefixer
// or ...
yarn add tailwindcss postcss autoprefixer

// Update with file below
// You can also do npx tailwindcss init, 
// but be sure to update the file
touch tailwind.config.js

// Update with file below
touch postcss.config.js
Enter fullscreen mode Exit fullscreen mode

Configuring tailwind and postcss

This is a basic setup that adds important! to all styles, this is not necessary for all projects, but I found it to be very helpful while working alongside Angular Material, which has quite a few very specific styles.

This also sets up purging of unused styles when built for production, otherwise you would end with very big style files.

// tailwind.config.js
module.exports = {
  important: true,
  purge: {
    enabled: process.env.NODE_ENV === "production",
    content: ["./src/**/*.{html,ts}"],
  },
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

This is a just bare bones config for postcss.

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
Enter fullscreen mode Exit fullscreen mode

Add tailwind styles to styles.css

Next step is to add the necessary imports to your styles.scss file.

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

Build for production

Finally, when you build for production, you have to use this line so postcss will purge the unused styles.

NODE_ENV=production ng build --prod
Enter fullscreen mode Exit fullscreen mode

Final thoughts

I wasn't sold on the Tailwindcss approach when it first came out, but after trying it in a few projects now I absolutely love it, it really is a breath of fresh air. I'm not a CSS expert by any stretch of the imagination and Tailwindcss helps me a lot in my work.

You can find a code only version of this at https://gitlab.com/-/snippets/2095311

Top comments (0)