Integrate Tailwind CSS with Angular

You don't know Tailwind CSS, yet? Then head over to their website, it's a damn nice CSS utility framework. If you, like me, want to integrate it with Angular, you find plenty of blog posts about it. Forget them all - some of them do strange stuff for the integration.

If you use Angular 11.2+, simple read the next section and skip the rest!

Angular 11.2+

This is the way to go with Angular 11.2+. It ships with native support for TailwindCSS.

  • Install TailwindCSS with npm install -D tailwindcss.
  • Optionally install some TailwindCSS plugins.
  • Create a tailwind.config.js in the root of your Angular project with the following content:
module.exports = {
  purge: ['./projects/**/*.html', './projects/**/*.ts'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};
  • Add to your styles.css file:
@tailwind base;
@tailwind components;
@tailwind utilities;

Alternatively you can also wait until ngx-tailwind supports Angular 11.2. It will automate the steps above with a single command. Yay!

Angular < 11.2

If you run Angular < 11.2 this section is for you. Otherwise, you don't need it, because with Angular 11.2+ it ships with a native integration of Tailwind CSS. How sweet!

The easiest way to integrate Tailwind CSS with Angular is by using ngx-tailwind by Marc Julian. Simply run ng add ngx-tailwind. Boom, done. Thanks Marc!

One more thing: don't forget to enable purging by updating your tailwind.config.js:

module.exports = {
-	purge: [],
+	purge: ['./projects/**/*.html', './projects/**/*.ts'],
	darkMode: false, // or 'media' or 'class'

Don't freak out, if your dev build is 15+ MB, the purging only works in production builds (or if you use NODE=production environment variable for dev builds).

Behind the scenes

If you're curious what happens behind the scenes, here is an explainer. Currently, you need a custom builder. Either Manfred Steyer's ngx-build-plus or @angular-builder/custom-webpack. The latter one does not seem to work correctly with Angular 11 and the integration of Tailwind CSS. Good thing, Marc did use ngx-build-plus.

Changes in angular.json

It swaps all three builders for ng build, ng serve and ng test commands like this:

- "builder": "@angular-devkit/build-angular:browser",
+ "builder": "ngx-build-plus:browser",
   options: {
+    "extraWebpackConfig": "webpack.config.js",
   }

Changes in package.json

Besides adding some more dependencies (ngx-build-plus, autoprefixer, postcss, tailwindcss and ngx-tailwind) you also get one more run script:

 "scripts":{
 	"lint": "ng lint",
-    "e2e": "ng e2e"
+    "e2e": "ng e2e",
+    "build:prod": "NODE_ENV=production ng build --prod"
  },

That task is used to create a production build, read about purging above!

New files

Last, it creates a webpack.config.js and tailwind.config.js both with the necessary lines of code to integrate Tailwind CSS.