Skip to content

屬性化 JSX 轉換器

在 JSX/TSX 中支持無值屬性化@unocss/transformer-attributify-jsx

示例

jsx
export function Component() {
  return (
    <div text-red text-center text-5xl animate-bounce>
      unocss
    </div>
  )
}

將被轉換為:

jsx
export function Component() {
  return (
    <div text-red="" text-center="" text-5xl="" animate-bounce="">
      unocss
    </div>
  )
}
沒有這個轉換器,JSX 會將無值屬性視為布爾屬性。
jsx
export function Component() {
  return (
    <div text-red={true} text-center={true} text-5xl={true} animate-bounce={true}>
      unocss
    </div>
  )
}

安裝

bash
pnpm add -D @unocss/transformer-attributify-jsx
bash
yarn add -D @unocss/transformer-attributify-jsx
bash
npm install -D @unocss/transformer-attributify-jsx
ts
// uno.config.ts
import { defineConfig, presetAttributify } from 'unocss'
import transformerAttributifyJsx from '@unocss/transformer-attributify-jsx'

export default defineConfig({
  // ...
  presets: [
    // ...
    presetAttributify(),
  ],
  transformers: [
    transformerAttributifyJsx(), // <--
  ],
})

注意事項

WARNING

規則與屬性化預設的規則幾乎相同,但有幾點需要注意。

html
<div translate-x-100% /> <!-- 不能以 `%` 結尾 -->

<div translate-x-[100px] /> <!-- 不能包含 `[` 或 `]` -->

相反,你可能想使用帶值的屬性:

html
<div translate="x-100%" />

<div translate="x-[100px]" />

黑名單

此轉換器只會轉換有效的 UnoCSS 實用類屬性。 你還可以使用 blocklist 繞過一些不需要轉換的屬性。

js
transformerAttributifyJsx({
  blocklist: [/text-[a-zA-Z]*/, 'text-5xl']
})
jsx
<div text-red text-center text-5xl animate-bounce>
  unocss
</div>

將被編譯為:

html
<div text-red text-center text-5xl animate-bounce="">
  unocss
</div>

Released under the MIT License.