stylex.env.*

Allows the user to configure shareable tokens and functions to be used within StyleX APIs. Values are configured through the babel config.

env is an experimental API that is subject to change.

const env: { [key: string]: mixed };

Values are replaced before compilation, so identical values always deduplicate into a single CSS rule. Unlike defineConsts, no additional CSS is generated.

Example use:

Configure env values in your babel plugin options:

babel.config.js
module.exports = {
  plugins: [
    ['@stylexjs/babel-plugin', {
      env: {
        tokens: {
          colors: {
            primary: '#0066ff',
            secondary: '#ff6600',
            background: 'white',
            text: 'black',
          },
          spacing: {
            small: '4px',
            medium: '8px',
            large: '16px',
          },
        },
      },
    }],
  ],
};

Then use them in any StyleX call:

import * as stylex from '@stylexjs/stylex';

const styles = stylex.create({
  root: {
    color: stylex.env.tokens.colors.primary,
    backgroundColor: stylex.env.tokens.colors.background,
    padding: stylex.env.tokens.spacing.medium,
  },
});

Nested objects can be passed directly to other StyleX APIs:

tokens.stylex.js
import * as stylex from '@stylexjs/stylex';

export const colors = stylex.defineVars(stylex.env.tokens.colors);

Functions

Define shareable functions using the env API. Functions must be pure and return strings or numbers.

babel.config.js
module.exports = {
  plugins: [
    ['@stylexjs/babel-plugin', {
      env: {
        opacity: (color, pct) =>
          `color-mix(in srgb, ${color} ${pct * 100}%, transparent)`,
        colorMix: (c1, c2, pct) =>
          `color-mix(in srgb, ${c1} ${pct}%, ${c2})`,
      },
    }],
  ],
};
import * as stylex from '@stylexjs/stylex';
import { colors } from './tokens.stylex';

const styles = stylex.create({
  root: {
    backgroundColor: stylex.env.colorMix(colors.primary, 'black', 80),
    boxShadow: `0 4px 4px ${stylex.env.opacity(colors.primary, 0.35)}`,
  },
});