Skip to content

defineStyleX NPM Version

稳定性: 实验性 ⚠️ 实验性功能,风险自负

<script setup> 定义与使用 StyleX 的 Atomic CSS-in-JS.

FeaturesSupported
Vue 3
Nuxt 3
TypeScript / Volar
Vue 2

配置

在使用这个宏之前,你需要先引入与配置 StyleX。步骤可能会有所变化,你可能需要查看 StyleX 官方文档 以及 StyleX 的第三方插件列表,以获取最新信息。

Vite

sh
pnpm add @stylexjs/stylex @stylex-extend/core @stylex-extend/vite -D
vite.config.ts
ts
import { stylex } from '@stylex-extend/vite'
import Vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import VueMacros from 'vue-macros/vite'

export default defineConfig({
  plugins: [
    VueMacros({
      plugins: {
        vue: Vue(),
      },
    }),
    stylex(), // 必须放在 Vue Macros 插件后
  ],
})
main.ts
ts
// 引入 StyleX 样式表, 参考:https://nonzzz.github.io/stylex-extend/integrations/vite
import 'virtual:stylex.css'

基本用法

App.vue
vue
<script setup lang="ts">
const 
styles
=
defineStyleX
({
red
: {
color
: 'red' },
}) // ... </script> <template> <
p
v-style
x="
styles
.
red
">Red</
p
>
</template>
编译结果(有所简化)
App.vue
vue
<script lang="ts">
const 
styles
=
_stylex_create
({
red
: {
color
: 'red' },
}) </script> <script setup lang="ts"> import {
create
as
_stylex_create
,
props
as
_stylex_props
,
} from '@stylexjs/stylex' // 虚拟模块,提供运行时代码 import
stylex_attrs
from '/vue-macros/define-stylex/stylex-attrs'
// ... </script> <template> <
p
v-bind="
stylex_attrs
(
_stylex_props
(
styles
.
red
))">Red</
p
>
</template>

条件样式

你可以应用多个样式,也可以根据条件应用样式。

App.vue
vue
<script setup lang="ts">
defineProps
<{
bold
?: boolean }>()
const
styles
=
defineStyleX
({
red
: {
color
: 'red' },
bold
: {
fontWeight
: 'bold' },
}) </script> <template> <
span
v-style
x="
(
styles
.
red
,
bold
&&
styles
.
bold
)
">Red</
span
>
</template>
编译结果(有所简化)
App.vue
vue
<script lang="ts">
const 
styles
=
_stylex_create
({
red
: {
color
: 'red' },
bold
: {
fontWeight
: 'bold' },
}) </script> <script setup lang="ts"> import {
create
as
_stylex_create
,
props
as
_stylex_props
,
} from '@stylexjs/stylex' import
stylex_attrs
from '/vue-macros/define-stylex/stylex-attrs'
defineProps
<{
bold
?: boolean }>()
</script> <template> <
span
v-bind="
stylex_attrs
(
_stylex_props
(
styles
.
red
,
bold
&&
styles
.
bold
))"
>Red</
span
> </template>

贡献者

页面历史

用 ❤️ 发电