跳到主要內容

變數定義

備註

必須在 StyleX Babel 設定檔中啟用 unstable_moduleResolution 選項才能啟用主題 API。

除了為產生原子樣式的元件撰寫樣式之外,StyleX 也提供 API 來以可靠、可預測且類型安全的的方式定義 CSS 自訂屬性 (CSS 變數)。

設計靈感

StyleX 中主題 API 的設計直接受到 React 的 Context API 啟發。變數的定義方式類似於建立 React Context,並且可以建立主題以「提供」這些變數的不同值,適用於 UI 子樹。

變數定義

使用 stylex.defineVars 函式定義一組變數

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

export const tokens = stylex.defineVars({
primaryText: 'black',
secondaryText: '#333',
accent: 'blue',
background: 'white',
lineColor: 'gray',
borderRadius: '4px',
fontFamily: 'system-ui, sans-serif',
fontSize: '16px',
});

這個函式也會在編譯時處理,並且會自動產生 CSS 變數名稱。

這會在 HTML 文件的 :root 中定義變數。它們可以當做常數匯入,並在 stylex.create 呼叫中使用。

使用媒體查詢

變數值可以根據媒體查詢而有所不同

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

類似地,也可以使用 @supports

定義變數時的規則

變數是唯一一種可以在 stylex.create 呼叫中使用的非區域值。這可以透過強制執行一些規則來實現

1. 變數必須定義在 .stylex.js 檔案中

變數必須在具有以下副檔名的檔案中

  1. .stylex.js
  2. .stylex.mjs
  3. .stylex.cjs
  4. .stylex.ts
  5. .stylex.tsx
  6. .stylex.jsx

2. 變數必須是命名匯出

每個 stylex.defineVars 呼叫必須為命名匯出。

允許:
// ✅ - Named export
export const colors = stylex.defineVars({
/* ... */
});

const sizeVars = { ... };
// ✅ - Another Named export
export const sizes = stylex.defineVars(sizeVars);
禁止:
// ❌ - Only named exports are allowed
export default stylex.defineVars({
/* ... */
});

// ❌ - The variable must be exported directly
const x = stylex.defineVars({
/* ... */
});
export const colors = x;

// ❌ - The variables cannot be nested within another object
export const colors = {
foregrounds: stylex.defineVars({
/* ... */
}),
backgrounds: stylex.defineVars({
/* ... */
}),
};

3. 檔案中不允許有其他匯出

目前,.stylex.js 檔案專門用於定義 CSS 變數。