Angular and TailwindCSS

Today we will have a look at setting up your new Angular app with TailwindCSS.

Setting up Angular

Angular 12 has just seen its release on May 12th. As with any Angular project before, there is not much different here. Simply run:

ng new MY_APP

and choose your options for stylesheets and routing as requested by the Angular CLI.

Adding TailwindCSS

Since Angular 11.2, the support for TailwindCSS comes out of the box. It's super simple now, all we have to do is:

npm install -D tailwindcss

Afterwards we'll need to create a tailwind.config.js file in the root of our project with the following settings:

module.exports = {
  purge: {
    enabled: process.env.NODE_ENV === "production",
    content: ["./src/**/*.{html,ts}"],
  },
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

The purge option will enable tree shaking, making sure we don't bundle unneeded Tailwind classes with our app. This saves a few MB, so should definitely be enabled in your production build.

Permanently enabling purging during development will prohibit any hot-reload style updates, as unused classes will be purged from your "ng serve" dev build as well.

You can find the rest of the configuration options in the documentation.

When this is done you still need to import Tailwind into your global stylesheet. Depending on your choice of stylesheets:

SCSS:

@use "tailwindcss/base";
@use "tailwindcss/components";
@use "tailwindcss/utilities";

CSS:

@tailwind base;
@tailwind components;
@tailwind utilities;

To check if its working, simply remove the default app.component.html content generated by the CLI and add a button:

<button class="bg-blue-500 px-4 py-2 text-lg text-white rounded hover:bg-blue-700">Hello Tailwind</button>

Run "ng serve" and see it in action.

Congratulations, you just added Tailwind to your Angular app.

I hope you found this little tutorial helpful. Next week we'll have a look at how to replace Karma with Jest.

Take care,

Florian