Dynamic rules

Our fancy-purple rule works fine but what if we want lots of colors? Creating a separate rule for each color is a lot of work. Instead we can use dynamic rules.

Dynamic rules are rules with a regex in the name. Let’s make a dynamic fancy-(color here) utility that will change the color to the specified color.

The name should be this: /^fancy-(.*)$/

New to regex?

Inside of uno.config.js we can modify "fancy-purple" to accept a regex instead. The syntax changes slightly and now looks like this:

[/^fancy-(.*)$/, ([, c]) => ({ color: `${c}` })],

Matching numbers in regex

We now have this arrow function which starts with ([, c]) where c will match whatever is after fancy- and allow us to use the c value in ({ color: `${c}` }).

You should end up with something like this:

import { defineConfig, presetUno } from "unocss";
export default defineConfig({
presets: [presetUno()],
rules: [[/^fancy-(.*)$/, ([, c]) => ({ color: `${c}` })]],
});

After creating the new dynamic rule all of the text in the preview should have its own color.

Powered by WebContainers
Files
Preparing Environment
  • Installing dependencies
  • Starting http server