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!