@baukit/ui-tokens

中文文档
0.18.3发布于 2026/11/07MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 8693

Dependency-free design-token schema, validator, accessibility checker, and deterministic compiler for web and React Native.

原始使用文档
文档目录7 节
  1. Define and validate tokens
  2. Work with colors
  3. Check a semantic contrast matrix
  4. Calculate vertical layout
  5. Compile
  6. Enforce tokens with no-raw-color
  7. Boundaries

@baukit/ui-tokens

A dependency-free design-token schema, validator, accessibility checker, and deterministic compiler for web and React Native.

Define and validate tokens

import { checkContrast, parseTokens, type DesignTokens } from '@baukit/ui-tokens';

const tokens = parseTokens(untrustedJson);
const violations = checkContrast(tokens);

Colors are opaque #RGB or #RRGGBB sRGB values with light and dark variants. Color leaves require at least a semantic group and name. Typography, space, radius, motion, and elevation are named scales. contrastPairs declares foreground/background semantic paths; normal text must reach 4.5:1 and entries marked largeText must reach 3:1 in both themes. Validation errors include paths such as $.color.text.primary.light, while contrast failures include the calculated ratio.

Validation is handwritten rather than Zod-based: the schema is small, this keeps production dependencies at zero, and it enables diagnostics tailored to semantic token paths.

Work with colors

The color helpers accept three- or six-digit hexadecimal sRGB colors, with an optional #. Normalized and calculated colors use lowercase #rrggbb form.

import {
  blendColors,
  chooseReadableForeground,
  hexToRgb,
  normalizeHexColor,
  rgbToHex,
} from '@baukit/ui-tokens';

normalizeHexColor('09C'); // '#0099cc'
hexToRgb('#0099cc'); // { r: 0, g: 153, b: 204 }
rgbToHex({ r: 0, g: 153, b: 204 }); // '#0099cc'
blendColors('#ffffff', '#000000', 0.25); // '#404040'

const foreground = chooseReadableForeground('#005fcc', ['#ffffff', '#111111'], 4.5);
// { foreground: '#ffffff', ratio: 5.98..., meetsThreshold: true }

blendColors clamps its ratio to [0, 1]. chooseReadableForeground returns the first candidate that meets the threshold. If none passes, it returns the candidate with the highest ratio and sets meetsThreshold to false.

Check a semantic contrast matrix

DEFAULT_SEMANTIC_CONTRAST_REQUIREMENTS defines these role paths:

  • color.background.primary and color.background.elevated
  • color.text.primary and color.text.muted
  • color.border.primary and color.focus.ring
  • color.action.primary, color.action.onPrimary, color.action.secondary, and color.action.onSecondary
  • color.status.success, color.status.warning, color.status.danger, and their onSuccess, onWarning, and onDanger foregrounds

Text and labeled foregrounds require 4.5:1. Borders and focus rings require 3:1 against both background roles. The checker tests every requirement in the light and dark variants and returns every failure.

import {
  checkSemanticContrastMatrix,
  DEFAULT_SEMANTIC_CONTRAST_REQUIREMENTS,
} from '@baukit/ui-tokens';

const failures = checkSemanticContrastMatrix(tokens, [
  ...DEFAULT_SEMANTIC_CONTRAST_REQUIREMENTS,
  {
    foregroundRole: 'color.chart.label',
    backgroundRole: 'color.chart.background',
    minimumRatio: 4.5,
  },
]);

Pass a different list to replace the defaults. A missing role or a minimum outside the possible WCAG range of 1 through 21 throws a descriptive error.

Calculate vertical layout

Products supply every dimension and threshold. Both functions reject negative or non-finite values.

import { getUsableContentHeight, isShortViewport } from '@baukit/ui-tokens';

getUsableContentHeight(720, 112, 128); // 480
isShortViewport(600, productLayout.shortViewportHeight); // true

Compile

import { toCssVariables, toReactNative } from '@baukit/ui-tokens';

const css = toCssVariables(tokens);
const nativeModule = toReactNative(tokens);

toCssVariables emits sorted --bk-* declarations in :root, then dark color overrides under [data-theme="dark"]. toReactNative emits a sorted nested tokens constant with an inferred Tokens type. Accessibility declarations are build metadata and are omitted from generated runtime constants.

Enforce tokens with no-raw-color

The design-token schema is only worth having if colors stay out of components. @baukit/ui-tokens/eslint ships an ESLint flat-config plugin that reports CSS colors written directly in application code.

import uiTokens from '@baukit/ui-tokens/eslint';

export default [
  {
    plugins: { '@baukit/ui-tokens': uiTokens },
    rules: {
      '@baukit/ui-tokens/no-raw-color': [
        'error',
        { allowedFiles: ['src/theme/tokens.ts', 'src/theme/**'] },
      ],
    },
  },
];

configs.recommended turns the rule on with defaults when a product needs no options:

import { configs } from '@baukit/ui-tokens/eslint';

export default [configs.recommended];

The rule reports #rgb, #rrggbb, and #rrggbbaa hex values plus rgb(), rgba(), hsl(), and hsla() anywhere they appear, in string and template literals alike. CSS color keywords such as crimson are reported only in a style-like position: a color-named property, a StyleSheet.create call, a style, color, or fill JSX attribute, a css tagged template, or a variable whose name ends in style, theme, palette, or colors. That restriction keeps route names, test ids, and ordinary prose off the report.

Options:

OptionDefaultMeaning
allowedFiles[]Glob-like paths that may declare raw colors. * matches inside a path segment, ** across segments. Put the token definition here.
allowedValuestransparent, currentColor, inherit, noneLiterals allowed everywhere. Entries add to the defaults.
additionalStyleProperties[]Extra property or attribute names treated as style-like.
reportKeywordstrueSet to false to report only hex and functional notations.

Boundaries

This package shares semantic values such as color.background.primary. It is deliberately not a design system and not a cross-platform component library: DOM and React Native components, interaction behavior, raw brand-palette decisions, and product themes all stay outside it.

exampleTokens demonstrates every group as a test fixture. It is not a Baukit visual language, and copying it into a product as a starting palette is not what it is for.

The production entry point has no runtime dependencies. eslint is an optional peer dependency reached only through the /eslint subpath, so importing the package never loads it.

版本与发布记录

@baukit/ui-tokens 共发布 67 个版本,首次发布于 2026/08/26;过去 12 个月发布了 67 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.18.3latest2026/11/07今天
0.18.22026/11/061 天前
0.18.12026/11/062 天前
0.18.02026/11/052 天前
0.17.12026/11/034 天前
0.17.02026/11/025 天前

关于 @baukit/ui-tokens 的常见问题

@baukit/ui-tokens 是什么?

Dependency-free design-token schema, validator, accessibility checker, and deterministic compiler for web and React Native.

如何安装 @baukit/ui-tokens?

在项目目录运行 npm install @baukit/ui-tokens,或使用 pnpm add / yarn add / bun add。

@baukit/ui-tokens 支持 TypeScript 吗?

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

@baukit/ui-tokens 支持 ESM 还是 CommonJS?

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

@baukit/ui-tokens 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@baukit/ui-tokens 可以商用吗?

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

@baukit/ui-tokens 的下载量有多少?

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

@baukit/ui-tokens 还在维护吗?

最新版本 0.18.3 发布于 2026/11/07(今天);至今共发布 67 个版本,其中过去 12 个月发布了 67 个;首次发布于 2026/08/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。