ElianCodes

← Back to blog

Implementing UnoCSS in Astro

UnoCSS is a CSS engine, built by Anthony Fu. Itā€™s rather a CSS engine than a CSS library. Itā€™s crazy fast, supports presets and is designed for flexibility and performance. I wanted to give this one a try, since I met Anthony last week at JSWorld, and Iā€™m totally blast away by his work.

Astro Integration

Itā€™s quite easy, since UnoCSS has a third party integration for Astro (thus you canā€™t install it through astro add CLI). Letā€™s take a look at how to implement it.

Letā€™s first install the integration for Astro and the reset package.

pnpm add @unocss/astro @unocss/reset

Now, since we didnā€™t use astro add to install the integration, we need to add it to our astro.config.mjs file manually.

Also, I noticed that the integration doesnā€™t work wit Node < v18, so be sure youā€™re on Node v18!

import { defineConfig } from "astro/config";
import unocss from "@unocss/astro";

export default defineConfig({
  integrations: [
    /* ... */
    unocss(),
  ],
});

Now you should have a clean and resetted website. Letā€™s add an integration to start writing utility-first CSS.

Presets and Configuration

pnpm add @unocss/preset-wind
import { defineConfig } from "astro/config";
import unocss from "@unocss/astro";
import presetWind from "@unocss/preset-wind";

// https://astro.build/config
export default defineConfig({
  integrations: [
    unocss({
      presets: [
        presetWind(),
        /* more presets */
      ],
      safelist: [
        /* this you can use to exclude utilities from purge */
      ],
    }),
  ],
});

Now you can use all the classes / utilities from the WindCSS library, in UnoCSS!

Of course, there are many many more presets available, you can check them out here.

Another awesome usecase and one of the drivers for me to use it, is the integration from UnoCSS with pure CSS icons! You can find that part of the repo here, but itā€™s quite easy and straightforward.

Tag me on Twitter if you have any questions or feedback!

Written by Elian Van Cutsem

← Back to blog