Skip to main content

Using variables

Note

The unstable_moduleResolution option needs to be enabled in the StyleX Babel configuration to enable theming APIs.

Once variables have been defined, they can be imported and used to declare styles with stylex.create.

Assume the following variables have been defined in a file called tokens.stylex.js:

tokens.stylex.js
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'},
borderRadius: '4px',
fontFamily: 'system-ui, sans-serif',
fontSize: '16px',
});

These styles can then imported and used like so:

components/MyComponent.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from '../tokens.stylex';

const styles = stylex.create({
container: {
color: colors.primaryText,
backgroundColor: colors.background,
padding: spacing.medium,
},
});

Rules when using variables

There are a few rules to keep in mind when using variables:

  1. Named imports must be used for importing variables.
  2. Variables must be imported directly from the .stylex.js files that define them.
tip

Remember that StyleX variables are comprised of CSS identifiers. They cannot be used as values within JavaScript code.