Installation
StyleX Variants is an ESM package for Vite applications using StyleX. You need StyleX, the variants package, and the Babel and Vite integrations that compile both libraries at build time.
Install the packages
- npm
- pnpm
- yarn
npm install @stylex-variants/core @stylexjs/stylex
npm install -D @babel/core@^8 @rolldown/plugin-babel @stylexjs/unplugin
pnpm add @stylex-variants/core @stylexjs/stylex
pnpm add -D @babel/core@^8 @rolldown/plugin-babel @stylexjs/unplugin
yarn add @stylex-variants/core @stylexjs/stylex
yarn add --dev @babel/core@^8 @rolldown/plugin-babel @stylexjs/unplugin
The package currently targets ESM consumers and is verified with Vite 8, Babel 8 and StyleX 0.19.1.
Configure Vite
Configure the variants Babel plugin before the StyleX plugin in Vite:
import babel from "@rolldown/plugin-babel";
import stylex from "@stylexjs/unplugin/vite";
import variants from "@stylex-variants/core/babel";
import react from "@vitejs/plugin-react";
export default {
plugins: [react(), babel({ plugins: [variants] }), stylex()],
};
The order is significant: StyleX Variants first expands the sxv recipe and
the StyleX plugin then compiles the resulting styles. Import a CSS asset from
the application entry point so Vite has an output asset for the generated
StyleX rules in production:
import "./index.css";
Create your first recipe
import { sxv } from "@stylex-variants/core";
const button = sxv({
base: { display: "inline-flex" },
variants: {
tone: {
primary: { backgroundColor: "blue", color: "white" },
neutral: { backgroundColor: "gray", color: "black" },
},
},
defaultVariants: { tone: "primary" },
});
export function Button() {
return <button {...button({ tone: "primary" })}>Continue</button>;
}
The Babel transform must run during the build. Calling sxv() without the
transform is unsupported and throws a configuration error.