### Install StyleX Compiler Plugins
Source: https://stylexjs.com/docs/learn/installation
Install the necessary Babel and PostCSS plugins for build-time style transformation.
```bash
npm install --save-dev @stylexjs/babel-plugin @stylexjs/postcss-plugin postcss
```
```bash
pnpm add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin postcss
```
```bash
yarn add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin postcss
```
```bash
bun add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin postcss
```
--------------------------------
### Install StyleX dependencies
Source: https://stylexjs.com/docs/llm-resources
Install the core runtime and the appropriate plugin for your specific build environment.
```bash
# Core runtime (always needed)
npm install @stylexjs/stylex
# For Vite, Rollup, Webpack, esbuild, or Rspack
npm install --save-dev @stylexjs/unplugin
# For Next.js
npm install --save-dev @stylexjs/babel-plugin @stylexjs/postcss-plugin
```
--------------------------------
### Install @stylexjs/unplugin
Source: https://stylexjs.com/docs/api/configuration/unplugin
Installation commands for various package managers.
```bash
npm install --save-dev @stylexjs/unplugin
```
```bash
pnpm add -D @stylexjs/unplugin
```
```bash
yarn add -D @stylexjs/unplugin
```
```bash
bun add -D @stylexjs/unplugin
```
--------------------------------
### Example useLayers Configuration
Source: https://stylexjs.com/docs/api/configuration/babel-plugin
An example of configuring useLayers with before, after, and prefix options to manage CSS layer ordering.
```typescript
const css = styleXTransform.processStylexRules(rules, {
useLayers: {
before: ['reset', 'base'],
after: ['utilities'],
prefix: 'stylex',
},
});
```
--------------------------------
### Install StyleX dependencies
Source: https://stylexjs.com/docs/learn/installation/postcss
Install the required Babel and PostCSS plugins using your preferred package manager.
```bash
npm install --save-dev @stylexjs/babel-plugin @stylexjs/postcss-plugin
```
```bash
pnpm add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin
```
```bash
yarn add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin
```
```bash
bun add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin
```
--------------------------------
### Install StyleX Runtime
Source: https://stylexjs.com/docs/learn/installation
Install the core StyleX runtime package using your preferred package manager.
```bash
npm install --save @stylexjs/stylex
```
```bash
pnpm add @stylexjs/stylex
```
```bash
yarn add @stylexjs/stylex
```
```bash
bun add @stylexjs/stylex
```
--------------------------------
### Defining Styles with stylex.create
Source: https://stylexjs.com/docs/api/javascript/create
Usage example demonstrating how to define static and dynamic styles using stylex.create.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
backgroundColor: 'red',
padding: '1rem',
paddingInlineStart: '2rem',
},
dynamic: (r, g, b) => ({
color: `rgb(${r}, ${g}, ${b})`,
}),
});
```
--------------------------------
### Install StyleX ESLint Plugin
Source: https://stylexjs.com/docs/llm-resources
Install the required ESLint plugin as a development dependency.
```bash
npm install --save-dev @stylexjs/eslint-plugin
```
--------------------------------
### Install @stylexjs/atoms
Source: https://stylexjs.com/docs/api/javascript/atoms
Install the package via npm.
```bash
npm install @stylexjs/atoms
```
--------------------------------
### Install StyleX CLI
Source: https://stylexjs.com/docs/learn/installation/cli
Install the CLI package as a development dependency using your preferred package manager.
```bash
npm install --save-dev @stylexjs/cli
```
```bash
pnpm add -D @stylexjs/cli
```
```bash
yarn add -D @stylexjs/cli
```
```bash
bun add -D @stylexjs/cli
```
--------------------------------
### Install StyleX ESLint Plugin
Source: https://stylexjs.com/docs/learn/installation
Install the ESLint plugin to catch invalid styles and enforce best practices.
```bash
npm install --save-dev @stylexjs/eslint-plugin
```
```bash
pnpm add -D @stylexjs/eslint-plugin
```
```bash
yarn add -D @stylexjs/eslint-plugin
```
```bash
bun add -D @stylexjs/eslint-plugin
```
--------------------------------
### Scaffold a new StyleX project
Source: https://stylexjs.com/docs/learn/installation/create
Initializes a new project using the official template and installs necessary dependencies.
```bash
npm create @stylexjs my-app
```
--------------------------------
### Setup Root Layout for StyleX
Source: https://stylexjs.com/docs/learn/installation/vite/sveltekit
Import the CSS entrypoint and configure hot reloading for development environments within the root layout component.
```svelte
{#if import.meta.env.DEV}
{/if}
{@render children()}
```
--------------------------------
### Configure Production Build with Bun.build
Source: https://stylexjs.com/docs/learn/installation/bun
Example of using the StyleX esbuild plugin within a Bun build script.
```javascript
import stylex from '@stylexjs/unplugin';
await Bun.build({
entrypoints: ['src/main.jsx'],
outdir: 'dist',
target: 'browser',
metafile: true,
plugins: [
stylex.esbuild({
useCSSLayers: true,
importSources: ['@stylexjs/stylex'],
unstable_moduleResolution: { type: 'commonJS' },
}),
],
});
```
--------------------------------
### Applying a theme with stylex.createTheme
Source: https://stylexjs.com/docs/api/javascript/createTheme
Usage example demonstrating how to override defined variables and apply the resulting theme to a component.
```javascript
import * as stylex from '@stylexjs/stylex';
import { colors } from './vars.stylex.js';
const theme = stylex.createTheme(colors, {
accentColor: 'red',
backgroundColor: 'gray',
lineColor: 'purple',
textPrimaryColor: 'black',
textSecondaryColor: 'brown',
});
function App() {
return (
);
}
```
--------------------------------
### Use StyleX CLI
Source: https://stylexjs.com/docs/llm-resources
Install and execute the StyleX CLI to process files outside of a bundler environment.
```bash
npm install --save-dev @stylexjs/cli
npx stylex --input ./src --output ./dist
```
--------------------------------
### Scaffold without dependency installation
Source: https://stylexjs.com/docs/learn/installation/create
Uses the --no-install flag to skip the automatic installation of dependencies.
```bash
npm create @stylexjs my-app -- --no-install
```
--------------------------------
### Configure @stylexjs/valid-styles rule
Source: https://stylexjs.com/docs/api/configuration/eslint-plugin
Example configuration for the @stylexjs/valid-styles rule using propLimits.
```json
{
"rules": {
"@stylexjs/valid-styles": [
"error",
{
"propLimits": {
"mask+([a-zA-Z])": {
"limit": null,
"reason": "Use the `mask` shorthand property instead."
},
"fontSize": {
"limit": "number",
"reason": "Only numeric font values are allowed"
},
"padding": {
"limit": [0, 4, 8, 16, 32, 64],
"reason": "Use a padding that conforms to the design system"
}
}
}
]
}
}
```
--------------------------------
### Configure @stylexjs/sort-keys rule
Source: https://stylexjs.com/docs/api/configuration/eslint-plugin
Example configuration for the @stylexjs/sort-keys rule.
```json
{
"rules": {
"@stylexjs/valid-styles": "error",
"@stylexjs/sort-keys": [
"warn",
{
"minKeys": 3,
"allowLineSeparatedGroups": true
}
]
}
}
```
--------------------------------
### Applying styles with stylex.props
Source: https://stylexjs.com/docs/api/javascript/props
Example of creating styles with stylex.create and applying them to a div using the spread operator.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
backgroundColor: 'red',
padding: '1rem',
paddingInlineStart: '2rem',
},
conditional: {
backgroundColor: 'blue',
},
dynamic: (opacity) => ({
opacity,
}),
});
;
```
--------------------------------
### Define basic button styles
Source: https://stylexjs.com/docs/learn/styling-ui/defining-styles
Initial setup for a button component style definition.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
button: {
backgroundColor: 'lightblue',
},
});
```
--------------------------------
### Customize animations with keyframes
Source: https://stylexjs.com/docs/api/javascript/viewTransitionClass
Example of using stylex.keyframes to define custom animations for view transitions.
```javascript
import * as stylex from '@stylexjs/stylex';
const fadeInUp = stylex.keyframes({
from: {
opacity: 0,
transform: 'translateY(-30px)',
},
to: {
opacity: 1,
transform: 'translateY(0px)',
},
});
const transitionCls = stylex.viewTransitionClass({
new: {
animationName: fadeInUp,
},
});
```
--------------------------------
### Configure Webpack for StyleX
Source: https://stylexjs.com/docs/learn/installation/webpack
Standard webpack.config.js setup including the StyleX plugin and MiniCssExtractPlugin for CSS handling.
```javascript
const fs = require('node:fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const stylex = require('@stylexjs/unplugin').default;
const templatePath = path.resolve(__dirname, 'index.html');
module.exports = {
// ...
devServer: {
watchFiles: [templatePath, path.resolve(__dirname, 'src/**/*')],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [{ loader: 'babel-loader' }],
},
{ test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] },
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
templateContent: () => fs.readFileSync(templatePath, 'utf-8'),
}),
stylex.webpack({
useCSSLayers: true,
// ... other StyleX configuration
}),
new MiniCssExtractPlugin(),
],
};
```
--------------------------------
### Apply position-try fallback
Source: https://stylexjs.com/docs/api/javascript/positionTry
Example of creating a position-try rule and applying it to an element using positionTryFallbacks.
```javascript
import * as stylex from '@stylexjs/stylex';
const fallback = stylex.positionTry({
positionAnchor: '--anchor',
top: '0',
left: '0',
width: '100px',
height: '100px',
});
const styles = stylex.create({
anchor: {
positionTryFallbacks: fallback,
},
});
```
--------------------------------
### Render DevStyleXInject in RootLayout
Source: https://stylexjs.com/docs/learn/installation/vite/waku
Example of rendering the DevStyleXInject component within the Waku root layout.
```tsx
// src/pages/_layout.tsx (excerpt)
import { DevStyleXInject } from '../components/DevStyleXInject';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<>
{children}
>
);
}
```
--------------------------------
### Using stylex.attrs in JSX
Source: https://stylexjs.com/docs/api/javascript/attrs
Example of applying stylex.attrs to a div element in a JSX environment.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
backgroundColor: 'red',
paddingInline: '1rem',
},
});
;
```
--------------------------------
### CSS Layer Output Example
Source: https://stylexjs.com/docs/api/configuration/unplugin
The resulting CSS structure when using CSS layers, featuring a layer-ordering header and wrapped rules.
```css
@layer reset, base, stylex.priority1, stylex.priority2, utilities;
@layer stylex.priority1 {
/* low-priority rules */
}
@layer stylex.priority2 {
/* higher-priority rules */
}
```
--------------------------------
### Run create package directly
Source: https://stylexjs.com/docs/learn/installation/create
Executes the package directly using npx with specified framework options.
```bash
npx @stylexjs/create my-app --framework vite-react
```
--------------------------------
### Configure StyleX CLI
Source: https://stylexjs.com/docs/learn/installation/cli
Define input/output directories, Babel presets, and StyleX configurations in a JSON5 file.
```json
{
input: ['./source'], // Where your StyleX source lives
output: ['./src'], // Where compiled files + CSS bundle are written
cssBundleName: 'stylex_bundle.css',
babelPresets: [
['@babel/preset-typescript', { allExtensions: true, isTSX: true }],
],
styleXConfig: {
aliases: {
'@/*': ['./source/*'],
},
},
// watch: true, // enable for incremental rebuilds
}
```
--------------------------------
### Configure Bun Dev Server Plugin
Source: https://stylexjs.com/docs/learn/installation/bun
Add the StyleX plugin entrypoint to your bunfig.toml file to enable CSS generation during development.
```toml
[serve.static]
plugins = ["@stylexjs/unplugin/bun"]
```
--------------------------------
### Define CSS entrypoint
Source: https://stylexjs.com/docs/learn/installation/nextjs
Import a CSS file in the root layout and include the @stylex directive to enable atomic CSS generation.
```css
/* app/globals.css */
@layer resets {
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
}
@stylex;
```
--------------------------------
### Handle numeric values
Source: https://stylexjs.com/docs/api/javascript/atoms
Use a leading underscore for values starting with a number; the compiler removes it.
```javascript
x.padding._16px;
x.fontSize._1rem;
```
--------------------------------
### Define CLI Scripts
Source: https://stylexjs.com/docs/learn/installation/cli
Add build and watch commands to your package.json to execute the StyleX compiler with a configuration file.
```json
{
"scripts": {
"build": "stylex --config .stylex.json5",
"watch": "stylex --config .stylex.json5 --watch"
}
}
```
--------------------------------
### Create a theme with stylex.createTheme
Source: https://stylexjs.com/docs/learn/theming/creating-themes
Define a theme by importing a variable group and providing override values, including support for media queries.
```javascript
import * as stylex from '@stylexjs/stylex';
import { colors, spacing } from './tokens.stylex';
// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';
// Dracula theme
export const dracula = stylex.createTheme(colors, {
primaryText: { default: 'purple', [DARK]: 'lightpurple' },
secondaryText: { default: 'pink', [DARK]: 'hotpink' },
accent: 'red',
background: { default: '#555', [DARK]: 'black' },
lineColor: 'red',
});
```
--------------------------------
### Configure esbuild
Source: https://stylexjs.com/docs/api/configuration/unplugin
Integrate StyleX into esbuild. Ensure metafile is enabled so the plugin can locate CSS outputs.
```javascript
import esbuild from 'esbuild';
import stylex from '@stylexjs/unplugin';
esbuild.build({
entryPoints: ['src/App.jsx'],
bundle: true,
metafile: true, // lets the plugin find CSS outputs
plugins: [stylex.esbuild({ useCSSLayers: true })],
});
```
--------------------------------
### Local style creation and application
Source: https://stylexjs.com/docs/learn/thinking-in-stylex
Demonstrates how StyleX compiles away create and props calls when styles are authored and consumed within the same file, resulting in zero runtime cost.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
red: { color: 'red' },
});
let a = stylex.props(styles.red);
```
```javascript
import * as stylex from '@stylexjs/stylex';
let a = { className: 'x1e2nbdu' };
```
```css
.x1e2nbdu {
color: red;
}
```
--------------------------------
### Create CSS entrypoint
Source: https://stylexjs.com/docs/llm-resources
Define the CSS entrypoint where StyleX will inject its generated styles, and import it into the application.
```css
/* src/index.css */
@stylex;
```
```typescript
import './index.css';
```
--------------------------------
### sxPropName configuration
Source: https://stylexjs.com/docs/api/configuration/babel-plugin
Customizes the JSX prop name for applying styles. The transformation example shows how the shorthand is converted.
```typescript
sxPropName: string | false; // Default: 'sx'
```
```jsx
```
```jsx
```
--------------------------------
### Using styles across file boundaries
Source: https://stylexjs.com/docs/learn/thinking-in-stylex
Shows how StyleX handles styles passed across files, where the create call maps keys to class names and props are executed at runtime with minimal overhead.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
foo: {
color: 'red',
},
bar: {
backgroundColor: 'blue',
},
});
function MyComponent({ style }) {
return ;
}
```
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = {
foo: {
color: 'x1e2nbdu',
$$css: true,
},
bar: {
backgroundColor: 'x1t391ir',
$$css: true,
},
};
function MyComponent({ style }) {
return ;
}
```
```css
.x1e2nbdu {
color: red;
}
.x1t391ir {
background-color: blue;
}
```
--------------------------------
### Using stylex.firstThatWorks for Fallback Styles
Source: https://stylexjs.com/docs/api/javascript/firstThatWorks
Demonstrates providing multiple position values to ensure browser compatibility for sticky positioning.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
header: {
position: stylex.firstThatWorks('sticky', '-webkit-sticky', 'fixed'),
},
});
```
--------------------------------
### Configure StyleX for Next.js
Source: https://stylexjs.com/docs/llm-resources
Set up Babel and PostCSS configurations to support StyleX in a Next.js project.
```javascript
// babel.config.js
const path = require('path');
const dev = process.env.NODE_ENV !== 'production';
module.exports = {
presets: ['next/babel'],
plugins: [
[
'@stylexjs/babel-plugin',
{
dev,
runtimeInjection: false,
enableInlinedConditionalMerge: true,
treeshakeCompensation: true,
aliases: { '@/*': [path.join(__dirname, '*')] },
unstable_moduleResolution: { type: 'commonJS' },
},
],
],
};
```
```javascript
// postcss.config.js
const babelConfig = require('./babel.config');
module.exports = {
plugins: {
'@stylexjs/postcss-plugin': {
include: [
'src/**/*.{js,jsx,ts,tsx}',
'app/**/*.{js,jsx,ts,tsx}',
'pages/**/*.{js,jsx,ts,tsx}',
'components/**/*.{js,jsx,ts,tsx}',
],
babelConfig: {
babelrc: false,
parserOpts: { plugins: ['typescript', 'jsx'] },
plugins: babelConfig.plugins,
},
useCSSLayers: true,
},
autoprefixer: {},
},
};
```
```css
/* app/globals.css */
@stylex;
```
--------------------------------
### Apply viewTransitionClass with React
Source: https://stylexjs.com/docs/api/javascript/viewTransitionClass
Example of using viewTransitionClass to customize animation durations for old and new view transition states within a React component.
```javascript
import * as stylex from '@stylexjs/stylex';
import { unstable_ViewTransition as ViewTransition } from 'react';
const lingeringOldView = stylex.viewTransitionClass({
new: {
animationDuration: '1s',
},
old: {
animationDuration: '2s',
},
});
{/* ... */};
```
--------------------------------
### Scaffold with specific framework template
Source: https://stylexjs.com/docs/learn/installation/create
Uses the --framework flag to select a specific framework template during initialization.
```bash
npm create @stylexjs my-app -- --framework nextjs
```
--------------------------------
### Defining Global Variables
Source: https://stylexjs.com/docs/api/javascript/defineVars
Define variables as named exports in a .stylex.js or .stylex.ts file. Keys starting with '--' result in custom CSS property names.
```javascript
import * as stylex from '@stylexjs/stylex';
export const colors = stylex.defineVars({
accent: 'blue',
line: 'gray',
'--background': 'black',
});
```
--------------------------------
### stylex.createTheme()
Source: https://stylexjs.com/docs/api
Creates a theme based on defined variables.
```APIDOC
## stylex.createTheme()
### Description
Creates a theme by overriding a set of defined variables.
```
--------------------------------
### stylex.createTheme(vars, overrides)
Source: https://stylexjs.com/docs/api/javascript/createTheme
Creates a theme by overriding a set of variables defined with defineVars.
```APIDOC
## stylex.createTheme
### Description
Takes a variable set created with `defineVars()` and an object used to override the values of those variables. It returns a `StyleXStyles` object that can be passed to `props()` to apply the theme to an element root.
### Signature
`function createTheme(vars: Vars, overrides: { [key: keyof Vars]: string; }): StyleXStyles;`
### Parameters
- **vars** (Vars) - Required - The variable set created with `defineVars()`.
- **overrides** (Object) - Required - An object mapping variable keys to their new string values.
### Example
```javascript
import * as stylex from '@stylexjs/stylex';
import { colors } from './vars.stylex.js';
const theme = stylex.createTheme(colors, {
accentColor: 'red',
backgroundColor: 'gray',
lineColor: 'purple',
textPrimaryColor: 'black',
textSecondaryColor: 'brown',
});
function App() {
return (
);
}
```
```
--------------------------------
### Define styles with stylex.create
Source: https://stylexjs.com/docs/learn
Use the stylex.create API to define styles using a standard object syntax.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
width: '100%',
maxWidth: 800,
minHeight: 40,
},
});
```
--------------------------------
### Define styles with stylex.create
Source: https://stylexjs.com/docs/learn/styling-ui/defining-styles
Use the create function to define namespaces containing style objects. All values must be statically analyzable.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
base: {
fontSize: 16,
lineHeight: 1.5,
color: 'rgb(60,60,60)',
},
highlighted: {
color: 'rebeccapurple',
},
});
```
--------------------------------
### Create and apply themes
Source: https://stylexjs.com/docs/llm-resources
Use stylex.createTheme to override variable values for DOM sub-trees. Themes can be defined in any file and applied via the stylex.props helper.
```tsx
import * as stylex from '@stylexjs/stylex';
import { colors } from './tokens.stylex';
export const darkTheme = stylex.createTheme(colors, {
primary: 'lightblue',
text: 'white',
background: '#1a1a1a',
});
// Apply theme to a container
function App({ isDark, children }) {
return (
{children} {/* All descendants use theme values */}
);
}
```
--------------------------------
### Configure Bun
Source: https://stylexjs.com/docs/api/configuration/unplugin
Configuration for Bun production builds and development server.
```javascript
import stylex from '@stylexjs/unplugin';
await Bun.build({
entrypoints: ['src/main.jsx'],
outdir: 'dist',
metafile: true,
plugins: [stylex.esbuild({ useCSSLayers: true })],
});
```
```toml
[serve.static]
plugins = ["@stylexjs/unplugin/bun"]
```
--------------------------------
### Scaffold with custom template
Source: https://stylexjs.com/docs/learn/installation/create
Uses the --template flag to specify a custom GitHub repository as the project source.
```bash
npm create @stylexjs my-app -- --template github:user/repo/template
```
--------------------------------
### Configure PostCSS for StyleX
Source: https://stylexjs.com/docs/learn/installation/nextjs
Create a postcss.config.js file to process StyleX styles using the same configuration as the Babel plugin.
```javascript
const babelConfig = require('./babel.config');
module.exports = {
plugins: {
'@stylexjs/postcss-plugin': {
include: [
// when using a src folder:
'src/**/*.{js,jsx,ts,tsx}',
// app router:
'app/**/*.{js,jsx,ts,tsx}',
// pages router:
'pages/**/*.{js,jsx,ts,tsx}',
// other top-level folders:
'components/**/*.{js,jsx,ts,tsx}',
],
babelConfig: {
babelrc: false,
parserOpts: { plugins: ['typescript', 'jsx'] },
plugins: babelConfig.plugins,
},
useCSSLayers: true,
},
autoprefixer: {},
},
};
```
--------------------------------
### Configure Babel for StyleX
Source: https://stylexjs.com/docs/learn/installation/nextjs
Create a babel.config.js file to integrate the StyleX Babel plugin with Next.js presets.
```javascript
const path = require('path');
const dev = process.env.NODE_ENV !== 'production';
module.exports = {
presets: ['next/babel'],
plugins: [
[
'@stylexjs/babel-plugin',
{
dev,
runtimeInjection: false,
enableInlinedConditionalMerge: true,
treeshakeCompensation: true,
aliases: { '@/*': [path.join(__dirname, '*')] },
unstable_moduleResolution: { type: 'commonJS' },
// ... other StyleX configuration
},
],
],
};
```
--------------------------------
### Configure PostCSS
Source: https://stylexjs.com/docs/learn/installation/postcss
Create a postcss.config.mjs file to integrate the StyleX PostCSS plugin with your Babel configuration.
```javascript
import stylex from '@stylexjs/postcss-plugin';
import autoprefixer from 'autoprefixer';
import babelConfig from './babel.config.js';
export default {
plugins: [
stylex({
include: ['src/**/*.{ts,tsx}'],
useCSSLayers: true,
babelConfig,
}),
// ... other plugins
autoprefixer,
],
};
```
--------------------------------
### Configure include
Source: https://stylexjs.com/docs/api/configuration/postcss-plugin
Specifies paths or glob patterns to compile.
```typescript
include: string[] // Default: auto-discovered
```
--------------------------------
### Configure StyleX for esbuild
Source: https://stylexjs.com/docs/llm-resources
Integrate the StyleX plugin into the esbuild build script.
```javascript
// build.js
const esbuild = require('esbuild');
const stylex = require('@stylexjs/unplugin');
esbuild.build({
entryPoints: ['src/index.tsx'],
bundle: true,
outdir: 'dist',
plugins: [
stylex.esbuild({
useCSSLayers: true,
}),
],
});
```
--------------------------------
### stylex.create()
Source: https://stylexjs.com/docs/api
Creates a set of styles for use in components.
```APIDOC
## stylex.create()
### Description
Creates a set of styles that can be used with other StyleX functions to apply styles to elements.
```
--------------------------------
### Define CSS entrypoint
Source: https://stylexjs.com/docs/learn/installation/postcss
Include the @stylex directive in your global CSS file to mark where generated styles should be injected.
```css
@layer base {
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
/* other base styles */
}
@stylex;
```
--------------------------------
### Combine local and prop styles
Source: https://stylexjs.com/docs/learn/styling-ui/using-styles
Illustrates the idiomatic way to merge local styles with styles passed via props using stylex.props.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
base: {
/*...*/
},
});
function CustomComponent({ style }) {
return ;
}
```
--------------------------------
### Configure esbuild with StyleX
Source: https://stylexjs.com/docs/learn/installation/esbuild
Integration of the StyleX unplugin into an esbuild build script. Ensure metafile is set to true to allow the plugin to locate the emitted CSS asset.
```javascript
import esbuild from 'esbuild';
import stylex from '@stylexjs/unplugin';
esbuild.build({
entryPoints: ['src/App.jsx'],
bundle: true,
metafile: true, // lets StyleX find the emitted CSS asset
plugins: [
stylex.esbuild({
useCSSLayers: true,
importSources: ['@stylexjs/stylex'],
unstable_moduleResolution: { type: 'commonJS' },
// ... other StyleX configuration
}),
],
});
```
--------------------------------
### stylex.viewTransitionClass(options)
Source: https://stylexjs.com/docs/api/javascript/viewTransitionClass
Creates a set of ::view-transition pseudo-element rules tied to a single class name for customizing View Transition animations.
```APIDOC
## stylex.viewTransitionClass(options)
### Description
Creates a set of `::view-transition` pseudo-element rules tied to a single class name. This function returns a string representing the generated class name.
### Parameters
- **options** (ViewTransitionClassOptions) - Required - An object containing style definitions for pseudo-elements:
- **group** (RawStyles) - Optional - Maps to `::view-transition-group(*.theGeneratedClass)`
- **imagePair** (RawStyles) - Optional - Maps to `::view-transition-image-pair(*.theGeneratedClass)`
- **old** (RawStyles) - Optional - Maps to `::view-transition-old(*.theGeneratedClass)`
- **new** (RawStyles) - Optional - Maps to `::view-transition-new(*.theGeneratedClass)`
### Returns
- **string** - The generated class name to be applied to elements.
### Example
```javascript
import * as stylex from '@stylexjs/stylex';
const transitionCls = stylex.viewTransitionClass({
new: {
animationDuration: '1s',
},
old: {
animationDuration: '2s',
},
});
```
```
--------------------------------
### Define styles with stylex.create
Source: https://stylexjs.com/docs/llm-resources
Create style objects using namespaces containing CSS properties. Use longhand properties and single-value shorthands.
```tsx
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
container: {
display: 'flex',
alignItems: 'center',
padding: 16,
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: 'navy',
},
});
```
--------------------------------
### Configure Vite for StyleX in SvelteKit
Source: https://stylexjs.com/docs/learn/installation/vite/sveltekit
Add the StyleX plugin to the Vite configuration file, ensuring it is configured for SvelteKit compatibility.
```typescript
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [
sveltekit(),
{
...stylex.vite({
useCSSLayers: true,
}),
enforce: undefined,
},
],
});
```
--------------------------------
### Apply basic styles with stylex.props
Source: https://stylexjs.com/docs/learn/styling-ui/using-styles
Use the stylex.props function to convert defined styles into className and styles props for HTML elements.
```javascript
```
--------------------------------
### Use constants in stylex.create
Source: https://stylexjs.com/docs/api/javascript/defineConsts
Import and use the defined constants within stylex.create calls.
```javascript
import * as stylex from '@stylexjs/stylex';
import { breakpoints, zIndices, animations } from './constants.stylex.js';
const styles = stylex.create({
container: {
position: 'relative',
zIndex: zIndices.modal,
transitionTimingFunction: animations.easeInOut,
transitionDuration: animations.fast,
color: {
default: 'black',
[breakpoints.small]: 'red',
[breakpoints.medium]: 'blue',
[breakpoints.large]: 'green',
},
padding: {
default: 4,
[breakpoints.medium]: 8,
[breakpoints.large]: 16,
},
},
});
```
--------------------------------
### Configure ESLint for StyleX
Source: https://stylexjs.com/docs/learn/installation
Add the StyleX plugin and rules to your .eslintrc.js configuration file.
```javascript
module.exports = {
plugins: ['@stylexjs'],
rules: {
'@stylexjs/valid-styles': 'error',
'@stylexjs/no-unused': 'error',
'@stylexjs/valid-shorthands': 'warn',
'@stylexjs/sort-keys': 'warn',
},
};
```
--------------------------------
### Configure Rollup
Source: https://stylexjs.com/docs/api/configuration/unplugin
Integrate StyleX into a Rollup configuration.
```javascript
import stylex from '@stylexjs/unplugin';
export default {
plugins: [stylex.rollup({ useCSSLayers: true })],
};
```
--------------------------------
### Define StyleX variables
Source: https://stylexjs.com/docs/learn/theming/using-variables
Define theme tokens using defineVars, supporting media queries via constants.
```javascript
import * as stylex from '@stylexjs/stylex';
// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';
export const colors = stylex.defineVars({
primaryText: { default: 'black', [DARK]: 'white' },
secondaryText: { default: '#333', [DARK]: '#ccc' },
accent: { default: 'blue', [DARK]: 'lightblue' },
background: { default: 'white', [DARK]: 'black' },
lineColor: { default: 'gray', [DARK]: 'lightgray' },
});
export const spacing = stylex.defineVars({
none: '0px',
xsmall: '4px',
small: '8px',
medium: '12px',
large: '20px',
xlarge: '32px',
xxlarge: '48px',
xxxlarge: '96px',
});
```
--------------------------------
### Configure StyleX for Rollup
Source: https://stylexjs.com/docs/llm-resources
Integrate the StyleX plugin into the Rollup configuration.
```javascript
// rollup.config.js
import stylex from '@stylexjs/unplugin';
export default {
plugins: [
stylex.rollup({
useCSSLayers: true,
}),
],
};
```
--------------------------------
### Configure Vite for StyleX and RSC
Source: https://stylexjs.com/docs/learn/installation/vite/vite-rsc
Configure the Vite environment to support RSC, SSR, and client builds while integrating the StyleX plugin.
```typescript
import rsc from '@vitejs/plugin-rsc';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [
rsc(),
react(),
stylex.vite({
// ... StyleX configuration options
}),
],
environments: {
rsc: {
build: {
rollupOptions: { input: { index: './src/framework/entry.rsc.tsx' } },
},
},
ssr: {
build: {
rollupOptions: { input: { index: './src/framework/entry.ssr.tsx' } },
},
},
client: {
build: {
rollupOptions: {
input: { index: './src/framework/entry.browser.tsx' },
},
},
},
},
});
```
--------------------------------
### Define explicit light, dark, and system themes
Source: https://stylexjs.com/docs/learn/recipes/light-dark-themes
Create separate theme objects for different color schemes using stylex.createTheme.
```javascript
const lightVars = {
primaryColor: 'black',
...
};
export const light = stylex.createTheme(vars, lightVars);
const darkVars = {
primaryColor: 'white',
...
};
export const dark = stylex.createTheme(vars, darkVars);
const systemVars = {
primaryColor: {
default: 'black',
'@media (prefers-color-scheme: dark)': 'white',
},
...
};
export const system = stylex.createTheme(vars, systemVars);
```
--------------------------------
### Configure Vite
Source: https://stylexjs.com/docs/api/configuration/unplugin
Integrate StyleX into a Vite project. Keep the plugin before framework plugins to ensure Fast Refresh compatibility.
```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [stylex.vite({ useCSSLayers: true }), react()],
});
```
--------------------------------
### Configure StyleX for Rspack
Source: https://stylexjs.com/docs/llm-resources
Integrate the StyleX plugin into the Rspack configuration.
```javascript
// rspack.config.js
const stylex = require('@stylexjs/unplugin');
module.exports = {
plugins: [
stylex.rspack({
useCSSLayers: true,
}),
],
};
```
--------------------------------
### stylex.firstThatWorks
Source: https://stylexjs.com/docs/llm-resources
Provides browser compatibility fallbacks for CSS properties.
```APIDOC
## stylex.firstThatWorks(...values)
### Description
Accepts a list of values and applies the first one that the browser supports, useful for handling vendor prefixes or fallback values.
```
--------------------------------
### Configure CSS Layers in Vite
Source: https://stylexjs.com/docs/api/configuration/unplugin
Use the useCSSLayers option to define layer ordering and namespaces for StyleX CSS output.
```typescript
stylex.vite({
useCSSLayers: {
before: ['reset', 'base'],
after: ['utilities'],
prefix: 'stylex',
},
});
```
--------------------------------
### stylex.attrs(...styles)
Source: https://stylexjs.com/docs/api/javascript/props
Returns class and style attributes for use in frameworks like Solid, Svelte, Qwik, or Vue.
```APIDOC
## stylex.attrs(...styles)
### Description
Used for non-React frameworks to get class and a string style value directly.
### Parameters
- **...styles** (StyleXStyles[]) - Required - A list of StyleX styles to apply.
```
--------------------------------
### Configure Vite for StyleX
Source: https://stylexjs.com/docs/learn/installation/vite/redwoodsdk
Integrate the StyleX unplugin into the Vite configuration, ensuring devMode is set to css-only for Redwood compatibility.
```typescript
import { defineConfig } from 'vite';
import { redwood } from 'rwsdk/vite';
import { cloudflare } from '@cloudflare/vite-plugin';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [
cloudflare({ viteEnvironment: { name: 'worker' } }),
redwood(),
stylex.vite({
devMode: 'css-only',
devPersistToDisk: true,
dev: true,
runtimeInjection: false,
}),
],
});
```
--------------------------------
### stylex.createTheme
Source: https://stylexjs.com/docs/llm-resources
Creates a theme object that overrides variable values for DOM sub-trees.
```APIDOC
## stylex.createTheme(tokens, overrides)
### Description
Creates a theme that overrides variable values defined in tokens. The returned theme object can be applied to elements to affect all descendants.
### Parameters
- **tokens** (object) - Required - The token object created via defineVars.
- **overrides** (object) - Required - An object mapping token keys to new values.
```
--------------------------------
### Define variables with media queries
Source: https://stylexjs.com/docs/learn/theming/defining-variables
Apply media queries or @supports rules to variable values to handle different themes or device capabilities.
```javascript
import * as stylex from '@stylexjs/stylex';
// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';
export const colors = stylex.defineVars({
primaryText: { default: 'black', [DARK]: 'white' },
secondaryText: { default: '#333', [DARK]: '#ccc' },
accent: { default: 'blue', [DARK]: 'lightblue' },
background: { default: 'white', [DARK]: 'black' },
lineColor: { default: 'gray', [DARK]: 'lightgray' },
});
```
--------------------------------
### stylex.create(styles)
Source: https://stylexjs.com/docs/api/javascript/create
Defines a set of styles or dynamic style functions to be used with StyleX.
```APIDOC
## stylex.create
### Description
Takes a map of style objects and returns an object of compiled StyleX styles. The compiled StyleX styles are a mapping of keys to class names.
### Signature
```typescript
function create RawStyles}>(
styles: T,
): {[Key in keyof T]: StyleXStyles};
```
### Example
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
backgroundColor: 'red',
padding: '1rem',
paddingInlineStart: '2rem',
},
dynamic: (r, g, b) => ({
color: `rgb(${r}, ${g}, ${b})`,
}),
});
```
```
--------------------------------
### Configure Vite for StyleX
Source: https://stylexjs.com/docs/learn/installation/vite/vite-react
Add the StyleX plugin to the Vite configuration, ensuring it is placed before the React plugin.
```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [
stylex.vite({
useCSSLayers: true,
// ... other StyleX configuration options
}),
react(),
],
});
```
--------------------------------
### dev configuration
Source: https://stylexjs.com/docs/api/configuration/babel-plugin
When true, injects CSS rules at runtime and enables support for the StyleX Dev Tools Extension.
```typescript
dev: boolean; // Default: false
```
--------------------------------
### Configure StyleX for Vite
Source: https://stylexjs.com/docs/llm-resources
Add the StyleX plugin to the Vite configuration. Place it before the React plugin to ensure Fast Refresh functionality is preserved.
```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import stylex from '@stylexjs/unplugin';
export default defineConfig({
plugins: [
stylex.vite({
useCSSLayers: true,
}),
react(),
],
});
```
--------------------------------
### Configure Babel for StyleX
Source: https://stylexjs.com/docs/learn/installation
Add the @stylexjs/babel-plugin to your .babelrc.js file with appropriate environment settings.
```javascript
module.exports = {
presets: [
...
],
plugins: [
...,
[
"@stylexjs/babel-plugin",
{
dev: process.env.NODE_ENV === "development",
test: process.env.NODE_ENV === "test",
runtimeInjection: false,
treeshakeCompensation: true,
unstable_moduleResolution: {
type: "commonJS",
},
},
],
],
};
```
--------------------------------
### Configure Rspack
Source: https://stylexjs.com/docs/api/configuration/unplugin
Integrate StyleX into Rspack using the CssExtractRspackPlugin.
```javascript
const rspack = require('@rspack/core');
const stylex = require('@stylexjs/unplugin').default;
module.exports = {
plugins: [
stylex.rspack({}),
new rspack.CssExtractRspackPlugin({ filename: 'index.css' }),
],
};
```
--------------------------------
### Define fallback styles
Source: https://stylexjs.com/docs/llm-resources
Use stylex.firstThatWorks to provide a list of values for browser compatibility, where the first supported value is applied.
```tsx
const styles = stylex.create({
header: {
position: stylex.firstThatWorks('sticky', '-webkit-sticky', 'fixed'),
display: stylex.firstThatWorks('grid', 'flex'),
},
});
```
--------------------------------
### stylex.props(...styles)
Source: https://stylexjs.com/docs/api/javascript/props
Takes a StyleX style or array of styles and returns a props object containing className and style properties to be spread onto an element.
```APIDOC
## stylex.props(...styles)
### Description
Takes a StyleX style or array of StyleX styles, and returns a props object. Values can be null, undefined, or false. The return value should be spread onto an element to apply the styles.
### Signature
`function props(...styles: StyleXStyles[]): { className: string; style: { [key: string]: string }; };`
### Parameters
- **...styles** (StyleXStyles[]) - Required - A list of StyleX styles to apply.
```
--------------------------------
### Using Defined Variables
Source: https://stylexjs.com/docs/api/javascript/defineVars
Import variables defined via defineVars and use them within stylex.create calls.
```javascript
import * as stylex from '@stylexjs/stylex';
import { colors } from './vars.stylex.js';
const styles = stylex.create({
container: {
color: colors.accent,
backgroundColor: colors['--background'],
},
});
```
--------------------------------
### Import atoms
Source: https://stylexjs.com/docs/api/javascript/atoms
Use the default import to access the atoms object.
```javascript
import x from '@stylexjs/atoms';
```
--------------------------------
### Use light-dark() CSS function
Source: https://stylexjs.com/docs/learn/recipes/light-dark-themes
Simplify theme management by using the light-dark() CSS function within stylex.defineVars.
```javascript
export const vars = stylex.defineVars({
primaryColor: 'light-dark(black, white)',
...
});
```
--------------------------------
### Combine media queries and pseudo-selectors
Source: https://stylexjs.com/docs/learn/styling-ui/defining-styles
Style values can be nested to combine multiple conditions, with 'default' required for contextual styles.
```javascript
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
button: {
color: {
default: 'var(--blue-link)',
':hover': {
default: null,
'@media (hover: hover)': 'scale(1.1)',
},
':active': 'scale(0.9)',
},
},
});
```
--------------------------------
### env configuration
Source: https://stylexjs.com/docs/api/configuration/babel-plugin
Defines compile-time constants and functions available via stylex.env.
```typescript
env: { [key: string]: mixed }; // Default: {}
```
--------------------------------
### Consume shareable tokens
Source: https://stylexjs.com/docs/learn/recipes/shareable-tokens
Use stylex.env to reference tokens defined in the babel configuration within your application files.
```javascript
import * as stylex from '@stylexjs/stylex';
export const colors = stylex.defineVars(stylex.env.tokens.colors);
export const spacing = stylex.defineVars(stylex.env.tokens.spacing);
export const radii = stylex.defineVars(stylex.env.tokens.radii);
```
--------------------------------
### Configure StyleX for Webpack
Source: https://stylexjs.com/docs/llm-resources
Integrate the StyleX plugin into the Webpack configuration.
```javascript
// webpack.config.js
const stylex = require('@stylexjs/unplugin');
module.exports = {
plugins: [
stylex.webpack({
useCSSLayers: true,
}),
],
};
```
--------------------------------
### Provide context in App component
Source: https://stylexjs.com/docs/learn/recipes/context-driven-styles
Wrap components with the context provider to share the sidebar state.
```javascript
import { useState } from 'react';
import SidebarContext from './SidebarContext';
import Sidebar from './Sidebar';
export default function App() {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
return (