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 documentation and the documentation of vite-plugin-stylex for the latest information.
Vite
sh
pnpm add @stylexjs/stylex vite-plugin-stylex
ts
import Vue from '@vitejs/plugin-vue'
import VueMacros from 'unplugin-vue-macros/vite'
import { defineConfig } from 'vite'
import StyleX from 'vite-plugin-stylex'
export default defineConfig({
plugins: [
VueMacros({
plugins: {
vue: Vue(),
},
}),
StyleX(), // Must be placed after Vue Macros
],
})
vue
<style>
/* import StyleX stylesheet, according to https://github.com/HorusGoul/vite-plugin-stylex */
@stylex stylesheet;
</style>
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 {
attrs as _stylex_attrs,
create as _stylex_create,
} from '@stylexjs/stylex'
// ...
</script>
<template>
<p v-bind="_stylex_attrs(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 {
attrs as _stylex_attrs,
create as _stylex_create,
} from '@stylexjs/stylex'
defineProps<{ bold?: boolean }>()
</script>
<template>
<span v-bind="_stylex_attrs(styles.red, bold && styles.bold)">Red</span>
</template>