Skip to content

Атрибутивный пресет

Этот пресет включает режим атрибутивности для других пресетов.

Исходный код

Установка

bash
pnpm add -D @unocss/preset-attributify
bash
yarn add -D @unocss/preset-attributify
bash
npm install -D @unocss/preset-attributify
bash
bun add -D @unocss/preset-attributify
ts
import presetAttributify from '@unocss/preset-attributify'

export default defineConfig({
  presets: [
    presetAttributify({ /* параметры пресета */ }),
    // ...
  ],
})

TIP

Этот пресет включен в пакет unocss, вы также можете импортировать его оттуда:

ts
import { presetAttributify } from 'unocss'

Режим атрибутивности

Представьте, что у вас есть кнопка с использованием утилит Tailwind CSS. Когда список становится длиннее, он становится очень сложным для чтения и поддержки.

html
<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"
>
  Кнопка
</button>

В режиме атрибутивности вы можете разделить утилиты на атрибуты:

html
<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"
>
  Кнопка
</button>

Например, text-sm text-white может быть объединен в text="sm white" без дублирования одного и того же префикса.

Самоссылающийся префикс

Для утилит, таких как flex, grid, border, которые имеют утилиты с тем же префиксом, предусмотрено специальное значение ~.

Например:

html
<button class="border border-red">Кнопка</button>

Может быть записано как:

html
<button border="~ red">Кнопка</button>

Атрибутивность без значения

В дополнение к режиму атрибутивности Windi CSS, этот пресет также поддерживает атрибуты без значения.

Например,

html
<div class="m-2 rounded text-teal-400" />

теперь может быть

html
<div m-2 rounded text-teal-400 />

INFO

Примечание: При использовании JSX <div foo> может быть преобразовано в <div foo={true}>, что помешает UnoCSS сопоставить сгенерированные CSS-атрибуты. Чтобы решить эту проблему, вы можете попробовать использовать transformer-attributify-jsx вместе с этим пресетом.

Конфликты свойств

Если имя режима атрибутов конфликтует со свойствами элементов или компонентов, вы можете добавить префикс un-, чтобы быть специфичным для режима атрибутивности UnoCSS.

Например:

html
<a text="red">Это конфликтует со свойством `text` ссылок</a>
<!-- к -->
<a un-text="red">Цвет текста красный</a>

Префикс необязателен по умолчанию, если вы хотите принудительно использовать префикс, установите

ts
presetAttributify({
  prefix: 'un-',
  prefixedOnly: true, // <--
})

Вы также можете отключить сканирование определенных атрибутов:

ts
presetAttributify({
  ignoreAttributes: [
    'text'
    // ...
  ]
})

Поддержка TypeScript (JSX/TSX)

Создайте файл shims.d.ts со следующим содержимым:

По умолчанию тип включает общие атрибуты из @unocss/preset-wind3. Если вам нужны пользовательские атрибуты, обратитесь к исходному коду типа, чтобы реализовать свой собственный тип.

Vue

Начиная с Volar 0.36, теперь строго относится к неизвестным атрибутам. Чтобы отказаться, вы можете добавить следующий файл в свой проект:

ts
declare module '@vue/runtime-dom' {
  interface HTMLAttributes {
    [key: string]: any
  }
}
declare module '@vue/runtime-core' {
  interface AllowedComponentProps {
    [key: string]: any
  }
}
export {}

React

ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'

declare module 'react' {
  interface HTMLAttributes<T> extends AttributifyAttributes {}
}

Vue 3

ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'

declare module '@vue/runtime-dom' {
  interface HTMLAttributes extends AttributifyAttributes {}
}

SolidJS

ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'

declare module 'solid-js' {
  namespace JSX {
    interface HTMLAttributes<T> extends AttributifyAttributes {}
  }
}

Svelte & SvelteKit

ts
declare namespace svelteHTML {
  import type { AttributifyAttributes } from '@unocss/preset-attributify'

  type HTMLAttributes = AttributifyAttributes
}

Astro

ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'

declare global {
  namespace astroHTML.JSX {
    interface HTMLAttributes extends AttributifyAttributes { }
  }
}

Preact

ts
import type { AttributifyAttributes } from '@unocss/preset-attributify'

declare module 'preact' {
  namespace JSX {
    interface HTMLAttributes extends AttributifyAttributes {}
  }
}

Атрибутивность с префиксом

ts
import type { AttributifyNames } from '@unocss/preset-attributify'

type Prefix = 'uno:' // измените на свой префикс

interface HTMLAttributes extends Partial<Record<AttributifyNames<Prefix>, string>> {}

Options

strict

  • type: boolean
  • default: false

Only generate CSS for attributify or class.

prefix

  • type: string
  • default: 'un-'

The prefix for attributify mode.

prefixedOnly

  • type: boolean
  • default: false

Only match for prefixed attributes.

nonValuedAttribute

  • type: boolean
  • default: true

Support matching non-valued attributes.

ignoreAttributes

  • type: string[]

A list of attributes to be ignored from extracting.

trueToNonValued

  • type: boolean
  • default: false

Non-valued attributes will also match if the actual value represented in DOM is true. This option exists for supporting frameworks that encodes non-valued attributes as true. Enabling this option will break rules that ends with true.

Credits

Initial idea by @Tahul and @antfu. Prior implementation in Windi CSS by @voorjaar.

Released under the MIT License.