Preset Attributify
Esto habilita el modo attributify para otros presets.
Instalación
pnpm add -D @unocss/preset-attributify
yarn add -D @unocss/preset-attributify
npm install -D @unocss/preset-attributify
bun add -D @unocss/preset-attributify
import presetAttributify from '@unocss/preset-attributify'
export default defineConfig({
presets: [
presetAttributify({ /* opciones del preset */ }),
// ...
],
})
TIP
Este preset está incluido en el paquete unocss
, también puedes importarlo desde ahí:
import { presetAttributify } from 'unocss'
Modo Attributify
Imagina que tienes este botón usando utilidades de Tailwind CSS. Cuando la lista se hace más larga, se vuelve realmente difícil de leer y mantener.
<button
class="bg-blue-400 hover:bg-blue-500 text-sm text-white font-mono font-light py-2 px-4 rounded border-2 border-blue-200 dark:bg-blue-500 dark:hover:bg-blue-600"
>
Botón
</button>
Con el modo attributify, puedes separar las utilidades en atributos:
<button
bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
text="sm white"
font="mono light"
p="y-2 x-4"
border="2 rounded blue-200"
>
Botón
</button>
Por ejemplo, text-sm text-white
podría agruparse en text="sm white"
sin duplicar el mismo prefijo.
Auto-referencia de prefijo
Para utilidades como flex
, grid
, border
, que tienen las utilidades iguales al prefijo, se proporciona un valor especial ~
.
Por ejemplo:
<button class="border border-red">Botón</button>
Puede escribirse como:
<button border="~ red">Botón</button>
Attributify sin valor
Además del modo attributify de Windi CSS, este preset también soporta atributos sin valor.
Por ejemplo,
<div class="m-2 rounded text-teal-400" />
ahora puede ser
<div m-2 rounded text-teal-400 />
INFO
Nota: Si estás usando JSX, <div foo>
podría transformarse a <div foo={true}>
lo que hará que el CSS generado por UnoCSS falle al coincidir con los atributos. Para resolver esto, podrías querer probar transformer-attributify-jsx
junto con este preset.
Conflictos de propiedades
Si el nombre del modo de atributos alguna vez entra en conflicto con las propiedades de los elementos o componentes, puedes añadir el prefijo un-
para ser específico al modo attributify de UnoCSS.
Por ejemplo:
<a text="red">Esto entra en conflicto con la prop `text` de los enlaces</a>
<!-- a -->
<a un-text="red">Color de texto a rojo</a>
El prefijo es opcional por defecto, si quieres forzar el uso del prefijo, establece
presetAttributify({
prefix: 'un-',
prefixedOnly: true, // <--
})
También puedes deshabilitar el escaneo para ciertos atributos por:
presetAttributify({
ignoreAttributes: [
'text'
// ...
]
})
Soporte de TypeScript (JSX/TSX)
Crea shims.d.ts
con el siguiente contenido:
Por defecto, el tipo incluye atributos comunes de
@unocss/preset-wind3
. Si necesitas atributos personalizados, consulta la fuente del tipo para implementar tu propio tipo.
Vue
Desde Volar 0.36, ahora es estricto con atributos desconocidos. Para optar por salir, puedes añadir el siguiente archivo a tu proyecto:
declare module '@vue/runtime-dom' {
interface HTMLAttributes {
[key: string]: any
}
}
declare module '@vue/runtime-core' {
interface AllowedComponentProps {
[key: string]: any
}
}
export {}
React
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'react' {
interface HTMLAttributes<T> extends AttributifyAttributes {}
}
Vue 3
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module '@vue/runtime-dom' {
interface HTMLAttributes extends AttributifyAttributes {}
}
SolidJS
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'solid-js' {
namespace JSX {
interface HTMLAttributes<T> extends AttributifyAttributes {}
}
}
Svelte & SvelteKit
declare namespace svelteHTML {
import type { AttributifyAttributes } from '@unocss/preset-attributify'
type HTMLAttributes = AttributifyAttributes
}
Astro
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare global {
namespace astroHTML.JSX {
interface HTMLAttributes extends AttributifyAttributes { }
}
}
Preact
import type { AttributifyAttributes } from '@unocss/preset-attributify'
declare module 'preact' {
namespace JSX {
interface HTMLAttributes extends AttributifyAttributes {}
}
}
Attributify con Prefijo
import type { AttributifyNames } from '@unocss/preset-attributify'
type Prefix = 'uno:' // cámbialo a tu prefijo
interface HTMLAttributes extends Partial<Record<AttributifyNames<Prefix>, string>> {}
Opciones
strict
- tipo:
boolean
- predeterminado:
false
Solo generar CSS para attributify o clase.
prefix
- tipo:
string
- predeterminado:
'un-'
El prefijo para el modo attributify.
prefixedOnly
- tipo:
boolean
- predeterminado:
false
Solo coincidir para atributos con prefijo.
nonValuedAttribute
- tipo:
boolean
- predeterminado:
true
Soporte para coincidir atributos sin valor.
ignoreAttributes
- tipo:
string[]
Una lista de atributos para ser ignorados de la extracción.
trueToNonValued
- tipo:
boolean
- predeterminado:
false
Los atributos sin valor también coincidirán si el valor real representado en el DOM es true
. Esta opción existe para soportar frameworks que codifican atributos sin valor como true
. Habilitar esta opción romperá reglas que terminan con true
.
Créditos
Idea inicial por @Tahul y @antfu. Implementación previa en Windi CSS por @voorjaar.