# @gravity-ui/uikit-themer 中文文档

规范地址：https://npmcn.com/package/%40gravity-ui/uikit-themer/

版本：2\.1\.0
npm 元数据更新时间：2026-10-22T13:56:27.676Z
中文译文更新时间：2026-11-17T01:11:57.878Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gravity-ui/uikit-themer
原文对照：https://npmcn.com/package/%40gravity-ui/uikit-themer/?lang=original
项目主页：https://github.com/gravity-ui/uikit-themer#readme
源码仓库：https://github.com/gravity-ui/uikit-themer

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：322 kB，54 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2025-06-02T15:40:14.912Z
- 最新版本发布：2026-10-22T13:56:27.384Z
- 近 30 天下载量：12074（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：16（近 12 个月 8 个）

## 中文简介

用于操作主题的库 `@gravity-ui/uikit` 图书馆。 允许您使用方便的 API 分析已有主题并生成新主题 .

## 安装

```sh
npm install @gravity-ui/uikit-themer
```

也可以使用：`pnpm add @gravity-ui/uikit-themer`、`yarn add @gravity-ui/uikit-themer`、`bun add @gravity-ui/uikit-themer`

## README

# @gravity-ui/uikit-themer ! (简体中文) [![npm package](https://img.shields.io/npm/v/@gravity-ui/uikit-themer)](https://www.npmjs.com/package/@gravity-ui/uikit-themer) [![CI](https://img.shields.io/github/actions/workflow/status/gravity-ui/uikit-themer/.github/workflows/ci.yml?label=CI&logo=github)](https://github.com/gravity-ui/uikit-themer/actions/workflows/ci.yml?query=branch:main)

用于操作主题的库 `@gravity-ui/uikit` 图书馆。 允许您使用方便的 API 分析已有主题并生成新主题 .

## 特征

-   🎨 **主题生成** - 为重力UI创建新主题
-   📖 **主题解析** - 以CSS和JSON格式分析现有主题
-   🔄 **改划** - 转换CSS和JSON格式
-   🎨 **色彩管理** - 使用私人和公用事业的颜色
-   ✍️ **类型** - 配置字体和文本样式
-   📏 **边框** - 管理边界半径

## 安装

```shell
npm install @gravity-ui/uikit-themer
```

## 基本用途

### 主题生成

主题生成函数需要一个完整的主题对象. 为了方便,你可以使用 `DEFAULT_THEME` 并覆盖必要的参数.

⚠️ **说明**: 当修改底色时, 使用 `updateBaseColor` 而不是直接操纵,以确保私人颜色得到适当的再生.

```typescript
import { generateCSS, generateJSON, updateBaseColor, DEFAULT_THEME } from '@gravity-ui/uikit-themer';

// Recommended: Use updateBaseColor for modifying colors
const themeWithCustomColors = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'brand',
  value: {
    dark: '#007AFF',
    light: '#007AFF'
  }
});

// Generate CSS theme
const cssTheme = generateCSS({
  theme: themeWithCustomColors
});

// Generate JSON theme with typography changes
const jsonTheme = generateJSON({
  theme: {
    ...DEFAULT_THEME,
    typography: {
      ...DEFAULT_THEME.typography,
      fontFamilies: {
        ...DEFAULT_THEME.typography.fontFamilies,
        sans: {
          mainFont: 'SF Pro Text',
          fallbackFonts: ['Arial'],
        },
      }
    }
  }
});
```

### 分析已存在的主题

```typescript
import { parseCSS, parseJSON } from '@gravity-ui/uikit-themer';

// Parse CSS theme to internal GravityTheme
const parsedCssTheme = parseCSS(cssString);

// Parse JSON theme to internal GravityTheme
const parsedJsonTheme = parseJSON(jsonString);
```

### 在格式之间转换

```typescript
import { convertCSStoJSON, convertJSONtoCSS } from '@gravity-ui/uikit-themer';

// Convert CSS to JSON
const jsonFromCss = convertCSStoJSON(cssTheme);

// Convert JSON to CSS
const cssFromJson = convertJSONtoCSS(jsonTheme);
```

## API 参考

### 默认主题

图书馆提供 `DEFAULT_THEME` 常数,包含一个完整的重力UI主题的所有默认值。 这是创建自定义主题的建议起点.

⚠️ **重要**: 修改时 `baseColors`,使用 `updateBaseColor` 函数,而不是直接操作,以确保适当再生成私人颜色.

```typescript
import { DEFAULT_THEME, updateBaseColor } from '@gravity-ui/uikit-themer';
import type { GravityTheme } from '@gravity-ui/uikit-themer';

// Recommended: Use updateBaseColor for base color changes
const customTheme: GravityTheme = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'brand',
  value: {
    dark: '#FF3B30',
    light: '#FF3B30'
  }
});

// For other theme parts, direct modification is fine
const themeWithCustomTypography: GravityTheme = {
  ...customTheme,
  typography: {
    ...customTheme.typography,
    // typography modifications...
  }
};
```

### 彩色公用事业

```typescript
import {
  isColorCssVariable,
  isUtilityColorCssVariable,
  isPrivateColorCssVariable,
  parsePrivateColorCssVariable,
  createPrivateColorCssVariable,
  createUtilityColorCssVariable,
  getUtilityColorTypeFromCssVariable,
  updateBaseColor
} from '@gravity-ui/uikit-themer';

// Check CSS variable type
const isColor = isColorCssVariable('--g-color-base-brand');
const isUtility = isUtilityColorCssVariable('--g-color-text-primary');
const isPrivate = isPrivateColorCssVariable('--g-private-color-red-500');

// Parse private color variable
const {mainColorToken, privateColorToken} = parsePrivateColorCssVariable('--g-private-color-red-500');

// Create color variables
createPrivateColorCssVariable('brand', '200-solid') === '--g-color-private-brand-200-solid'
createUtilityColorCssVariable('text-link-visited') === '--g-color-text-link-visited'

// Get utility color type
getUtilityColorTypeFromCssVariable('--g-color-text-link-hover') === 'text-link-hover'
```

#### 更新底色

⚠️ **重要**: 总是使用 `updateBaseColor` 当修改底色以确保私人颜色的正确再生时.

```typescript
import { updateBaseColor, DEFAULT_THEME } from '@gravity-ui/uikit-themer';

// Update base color for a single theme variant
const updatedTheme = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'brand',
  themeVariant: 'light',
  value: '#007AFF',
});

// Update base color for both theme variants
const updatedBothThemes = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'brand',
  value: {
    light: '#007AFF',
    dark: '#0056CC',
  },
});

// Create a new color token
const newColorTheme = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'custom-accent',
  value: {
    light: '#FF6B35',
    dark: '#FF8C5A',
  },
});
```

这个 `updateBaseColor` 函数 :

-   更新基准颜色 `baseColors`
-   自动再生相应的私有颜色
-   保持主题不可改变性( 返回新主题对象)
-   处理已有和新的颜色符号
-   支持同时更新单个主题变量或两个变量

**为什么用 `updateBaseColor`? 吗?**

直接修改 `baseColors` 不重生出私人色彩,会导致主题不一致. 私用颜色由底色来计算,并在整个UI组件中使用. 这个 `updateBaseColor` 函数确保:

1.  适当更新了底色
2.  使用新基色重新生成私有颜色
3.  主题在内部保持不变
4.  所有颜色依赖关系都得到维护

### 类型

使用字体和文字样式.

```typescript
import {
  isTextCssVariable,
  isFontCssVariable,
  createFontCssVariable,
  createTextCssVariable,
  getKeyFromCssFontVariable,
  parseTextCssVariable,
  generateCssFontFamily,
  TEXT_VARIANTS,
  TEXT_GROUP_PROPERTIES,
  TEXT_VARIANT_PROPERTIES
} from '@gravity-ui/uikit-themer';
import type {
  TypographyOptions,
  TextGroup,
  TextVariant,
  FontOptions
} from '@gravity-ui/uikit-themer';

// Check typography CSS variables
const isText = isTextCssVariable('--g-text-body-1-font-size');
const isFont = isFontCssVariable('--g-font-family-sans');

// Create typography variables
createFontCssVariable('additional') === '--g-font-family-additional';

createTextCssVariable({
    variant: 'body-1',
    property: 'font-size'
}) === '--g-text-body-1-font-size'

// Utilities
getKeyFromCssFontVariable('--g-font-family-sans') === 'sans'

parseTextCssVariable('--g-text-body-1-font-size') === {
    "group": "body",
    "variant": "body-1",
    "property": "font-size"
}

generateCssFontFamily({
    "mainFont": "SF Pro Text",
    "fallbackFonts": ["Arial", "sans-serif"]
}) === "'SF Pro Text', 'Arial', 'sans-serif'"

// Constants
console.log(TEXT_VARIANTS); // All available text variants
console.log(TEXT_GROUP_PROPERTIES); // Text group properties
console.log(TEXT_VARIANT_PROPERTIES); // Text variant properties
```

**类型 :**

-   `TypographyOptions` - 打印选项
-   `TextGroup` - 文本组(机构、标题、显示等)
-   `TextVariant` - 文本变体
-   `TextBodyVariant`, (中文(简体) ), `TextCaptionVariant`, (中文(简体) ), `TextHeaderVariant` - 具体变体
-   `FontOptions` - 字体选项

### 边框

以边界半径工作.

```typescript
import {
  isBorderRadiusCssVariable,
  createBorderRadiusCssVariable,
  BORDER_SIZES
} from '@gravity-ui/uikit-themer';
import type { BorderSize } from '@gravity-ui/uikit-themer';

// Check border radius variable
const isBorderRadius = isBorderRadiusCssVariable('--g-border-radius-m');

// Create border radius variable
const borderVar = createBorderRadiusCssVariable('m');

// Available border sizes
console.log(BORDER_SIZES); // ['xs', 's', 'm', 'l', 'xl']
```

### 与 JSON 主题合作

```typescript
import {
  generateJSON,
  parseJSON,
  isValueWithReference,
  isThemizedValueWithReference
} from '@gravity-ui/uikit-themer';
import type {
  JsonTheme,
  ThemizedValueWithReference,
  ValueWithReference
} from '@gravity-ui/uikit-themer';

// Check values with references
const hasRef = isValueWithReference(value);
const hasThemizedRef = isThemizedValueWithReference(value);
```

**JSON类型:**

-   `JsonTheme` - JSON代表主题
-   `ThemizedValueWithReference` - 与实录参考值
-   `ValueWithReference` - 参考值

### 核心类型

```typescript
import type {
  GravityTheme,
  PrivateColorOptions,
  PrivateColors,
  BaseColors,
  ThemizedColorOptions,
  ColorOptions,
  Theme
} from '@gravity-ui/uikit-themer';
```

-   `GravityTheme` - 主要内部重力UI主题类型
-   `PrivateColorOptions` - 私人颜色选项
-   `PrivateColors` - 私人颜色
-   `BaseColors` - 基准颜色
-   `ThemizedColorOptions` - 主题化颜色选项
-   `ColorOptions` - 常规颜色选项
-   `Theme` - 通用主题类型(`light` | `dark`(中文(简体) )

## 实例

### 创建自定义主题

```typescript
import { generateCSS, updateBaseColor, DEFAULT_THEME } from '@gravity-ui/uikit-themer';

// Recommended: Use updateBaseColor to modify base colors
const themeWithCustomBrand = updateBaseColor({
  theme: DEFAULT_THEME,
  colorToken: 'brand',
  value: {
    dark: '#007AFF',
    light: '#007AFF'
  }
});

const customTheme = generateCSS({
  theme: {
    ...themeWithCustomBrand,
    typography: {
      ...themeWithCustomBrand.typography,
      fontFamilies: {
        ...themeWithCustomBrand.typography.fontFamilies,
        sans: {
          mainFont: 'SF Pro Text',
          fallbackFonts: ['Arial'],
        },
      },
      variants: {
        ...themeWithCustomBrand.typography.variants,
        'body-1': {
          'font-size': '13px',
          'line-height': '18px',
        }
      }
    }
  }
});
```

### 分析并修改已存在的主题

```typescript
import { parseCSS, generateCSS, updateBaseColor } from '@gravity-ui/uikit-themer';

// Parse existing theme
const existingTheme = parseCSS(cssString);

// Recommended: Use updateBaseColor to modify brand color
const modifiedTheme = updateBaseColor({
  theme: existingTheme,
  colorToken: 'brand',
  value: {
    dark: '#FF3B30',
    light: '#FF3B30'
  }
});

// Generate new CSS
const newCSS = generateCSS({theme: modifiedTheme});
```

### 使用特定主题部件

```typescript
import { generateCSS, DEFAULT_THEME } from '@gravity-ui/uikit-themer';

// Override only typography
const typographyOnlyTheme = generateCSS({
  theme: {
    ...DEFAULT_THEME,
    typography: {
      ...DEFAULT_THEME.typography,
      fontFamilies: {
        ...DEFAULT_THEME.typography.fontFamilies,
        'custom-font': {
          mainFont: 'SF Pro Text',
          fallbackFonts: ['Arial'],
        },
      },
      groups: {
        ...DEFAULT_THEME.typography.groups,
        body: {
          'font-family': 'custom-font',
          'font-weight': 400,
        },
      }
    }
  }
});
```

## 常见问题

### @gravity-ui/uikit-themer 是什么？

用于操作主题的库 @gravity-ui/uikit 图书馆。 允许您使用方便的 API 分析已有主题并生成新主题 \.

### 如何安装 @gravity-ui/uikit-themer？

在项目目录运行 npm install @gravity-ui/uikit-themer，或使用 pnpm add / yarn add / bun add。

### @gravity-ui/uikit-themer 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gravity-ui/uikit-themer 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gravity-ui/uikit-themer 可以商用吗？

@gravity-ui/uikit-themer 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gravity-ui/uikit-themer 的下载量有多少？

根据 npm 官方下载统计，@gravity-ui/uikit-themer 在 2026/10/17 – 2026/11/15 这 30 天内被下载 12,074 次，日均约 402 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gravity-ui/uikit-themer 还在维护吗？

最新版本 2\.1\.0 发布于 2026/10/22（25 天前）；至今共发布 16 个版本，其中过去 12 个月发布了 8 个；首次发布于 2025/06/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

