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.