定义变量
注意
需要在 StyleX Babel 配置中启用 unstable_moduleResolution
选项才能启用主题 API。
除了为生成原子样式的组件创作样式外,StyleX 还提供 API 以可靠、可预测和类型安全的方式定义 CSS 自定义属性(CSS 变量)。
设计灵感
StyleX 中主题 API 的设计直接受到 React 的 Context API 的启发。变量使用默认值定义,类似于创建 React 上下文的方式,并且可以创建主题以“提供”这些变量在 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
文件中定义
变量必须位于以下扩展名之一的文件中:
.stylex.js
.stylex.mjs
.stylex.cjs
.stylex.ts
.stylex.tsx
.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 变量。