defineStyleX
Stability:
experimental
⚠️ Experimental feature, use at your riskDefine and consume StyleX styles in <script setup>
.
Features | Supported |
---|---|
Vue 3 | ✅ |
Nuxt 3 | ✅ |
TypeScript / Volar | ✅ |
Vue 2 | ✅ |
Setup
To use StyleX, you should install and configure StyleX first. The steps could change, you may want to check the official document and the document of StyleX bundler integrations for the latest information.
Vite
sh
pnpm add @stylexjs/stylex @stylex-extend/core @stylex-extend/vite -D
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(), // Must be placed after Vue Macros
],
})
ts
// import StyleX stylesheet, according to https://nonzzz.github.io/stylex-extend/integrations/vite
import 'virtual:stylex.css'
Basic Usage
vue
<script setup lang="ts">
const styles = defineStyleX({
red: { color: 'red' },
})
// ...
</script>
<template>
<p v-stylex="styles.red">Red</p>
</template>
Compiled Code (with some simplifications)
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'
// virtual module to provide runtime code
import stylex_attrs from '/vue-macros/define-stylex/stylex-attrs'
// ...
</script>
<template>
<p v-bind="stylex_attrs(_stylex_props(styles.red))">Red</p>
</template>
Conditional Styles
Optional and multiple rules are supported.
vue
<script setup lang="ts">
defineProps<{ bold?: boolean }>()
const styles = defineStyleX({
red: { color: 'red' },
bold: { fontWeight: 'bold' },
})
</script>
<template>
<span v-stylex="(styles.red, bold && styles.bold)">Red</span>
</template>
Compiled Code (with some simplifications)
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>