メインコンテンツにスキップ

変数の使用

注記

テーマAPIを有効にするには、StyleX Babel設定でunstable_moduleResolutionオプションを有効にする必要があります。

変数が定義されたら、それらをインポートしてstylex.createでスタイルを宣言するために使用できます。

以下の変数が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'},
});

export const spacing = stylex.defineVars({
none: '0px',
xsmall: '4px',
small: '8px',
medium: '12px',
large: '20px',
xlarge: '32px',
xxlarge: '48px',
xxxlarge: '96px',
});

これらのスタイルは、次のようにインポートして使用できます。

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

変数を使用する際のルール

変数を使用する際に留意すべきいくつかのルールがあります。

  1. 変数をインポートするには、名前付きインポートを使用する必要があります。
  2. 変数は、それらを定義する.stylex.jsファイルから直接インポートする必要があります。
ヒント

StyleXの変数はCSS識別子で構成されていることを覚えておいてください。JavaScriptコード内の値として使用することはできません。