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 create.
Assume the following variables have been defined in a file called
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' },
});
export const spacing = stylex.defineVars({
none: '0px',
xsmall: '4px',
small: '8px',
medium: '12px',
large: '20px',
xlarge: '32px',
xxlarge: '48px',
xxxlarge: '96px',
});These styles can then be imported and used like so:
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:
- Named imports must be used for importing variables.
- Variables must be imported directly from the
.stylex.jsfiles that define them.
Remember that StyleX variables are comprised of CSS identifiers. They cannot be used as values within JavaScript code.