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)}`,
  },
});

TypeScript usage

You can use module declaration to override the env type to match your exact usage. You only need to do this once per project. As long as this file is included by your tsconfig it'll override the env type in all other files in this project.

Note: This approach doesn't currently check whether this type matches what you're passing to babel plugin options.

declare module '@stylexjs/stylex/lib/types/StyleXTypes' {
  interface Register {
    env: {
      tokens: {
        colors: {
          primary: string;
        };
      };
    };
  }
}

// Usage
stylex.env.tokens.colors.primary; // Type checks correctly and you get intellisense