写一个 story 把 CSS 自定义属性(变量)按颜色、间距分组展示

解读

面试官想验证三件事:

  1. 你是否真正理解 CSS 自定义属性(变量) 在前端工程中的价值,而不仅是“会写”。
  2. 你是否能用 Storybook 的 CSF3 格式 把“展示”做成可交互、可维护的文档,而不是静态页面。
  3. 你是否能把“分组”做成 可扩展的元数据驱动方案,方便后续新增变量、主题切换、暗色模式等需求,而不是 hard-code。

国内大厂组件库(如 Ant Design、TDesign)已把 Design Token 作为独立包发布,Storybook 是最直观的验收场所;这道题就是考察你能否把“变量”变成“资产”。

知识点

  1. CSS 自定义属性作用域::root 全局、[data-theme] 局部、.component 级联。
  2. Storybook 7 的 CSF3:meta 定义默认导出、story 用函数写法、render 可复用。
  3. addon-docs 的 Description 与 Source 插槽,可自动把变量注释渲染成表格(虽然题目禁用表格,但思路要懂)。
  4. CSSOM 读取:getComputedStyle(document.documentElement).getPropertyValue('--xxx'),用于运行时抓取变量,避免二次维护。
  5. 分组策略:用 命名约定 --color-*、--space-*,或运行时扫描并用正则归类;后者更健壮,可应对第三方包注入的变量。
  6. 暗色模式切换:利用 document.documentElement.toggleAttribute('data-dark'),story 里用 globals 控制,实现“一键验收”所有变量。
  7. 性能:一次性读取放入 Map,避免 getComputedStyle 在渲染循环里反复调用。

答案

以下代码基于 Storybook 7 + React 18 + TypeScript,直接放到 src/tokens/Variables.stories.tsx 即可运行。
思路:

  • 运行时扫描 :root 全部变量,按正则拆成 color / space / other 三组;
  • 用 globals 提供“暗色模式”开关,实时切换 data-theme;
  • 每个分组一个 story,源码即文档,方便面试官逐行 review。
import type { Meta, StoryObj } from '@storybook/react';
import { useEffect, useState } from 'react';

const meta: Meta = {
  title: 'Design Tokens/Variables',
  parameters: {
    layout: 'padded',
    docs: {
      description: {
        component: '展示 CSS 自定义属性(变量),按颜色、间距分组,支持暗色模式切换。',
      },
    },
  },
  argTypes: {
    dark: {
      control: 'boolean',
      description: '是否开启暗色模式',
    },
  },
  args: {
    dark: false,
  },
};
export default meta;

type Story = StoryObj<{ dark: boolean }>;

/* 运行时抓取变量并分组 */
function useCssVariables() {
  const [groups, setGroups] = useState<Record<string, Record<string, string>>>({});
  useEffect(() => {
    const computed = getComputedStyle(document.documentElement);
    const map: Record<string, Record<string, string>> = { color: {}, space: {}, other: {} };
    Array.from(computed)
      .filter((k) => k.startsWith('--'))
      .forEach((key) => {
        const value = computed.getPropertyValue(key).trim();
        const name = key.slice(2); // 去掉 --
        if (name.startsWith('color-')) map.color[name] = value;
        else if (name.startsWith('space-')) map.space[name] = value;
        else map.other[name] = value;
      });
    setGroups(map);
  }, []);
  return groups;
}

/* 渲染单个分组 */
const Group: React.FC<{ title: string; items: Record<string, string> }> = ({ title, items }) => (
  <section style={{ marginBottom: 32 }}>
    <h3 style={{ fontSize: '18px', margin: '16px 0 8px' }}>{title}</h3>
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
      {Object.entries(items).map(([name, value]) => (
        <div
          key={name}
          style={{
            padding: '8px 12px',
            border: '1px solid var(--color-border, #e6e8eb)',
            borderRadius: 6,
            minWidth: 160,
            background: name.startsWith('color-') ? value : undefined,
            color: name.startsWith('color-') ? '#fff' : undefined,
          }}
          title={`--${name}: ${value}`}
        >
          <div style={{ fontSize: 12, opacity: 0.65 }}>--{name}</div>
          <div style={{ fontSize: 14, marginTop: 4 }}>{value}</div>
        </div>
      ))}
    </div>
  </section>
);

/* 主组件 */
const VariablesPanel: React.FC<{ dark: boolean }> = ({ dark }) => {
  useEffect(() => {
    if (dark) {
      document.documentElement.setAttribute('data-theme', 'dark');
    } else {
      document.documentElement.removeAttribute('data-theme');
    }
  }, [dark]);

  const groups = useCssVariables();
  return (
    <article>
      <Group title="颜色 Color" items={groups.color || {}} />
      <Group title="间距 Space" items={groups.space || {}} />
      <Group title="其他 Other" items={groups.other || {}} />
    </article>
  );
};

/* Story 定义 */
export const Overview: Story = {
  render: (args) => <VariablesPanel {...args} />,
};

使用方式:

  1. 在 :root 里声明变量,例如
    :root{
      --color-primary: #1677ff;
      --space-xs: 4px;
    }
    [data-theme='dark']{
      --color-primary: #1668dc;
    }
    
  2. 运行 pnpm storybook,进入 Design Tokens/Variables 面板,打开右上角 暗色模式 开关,即可看到颜色实时切换。

该方案零硬编码,新增变量无需改 story,直接刷新即可;符合国内“组件即资产”的验收标准。

拓展思考

  1. 如何对接设计插件
    把 Figma 的 Design Token 插件导出 JSON,写个 vite-plugin-token 在开发阶段把 JSON 注入为 :root 变量,story 里即可实时同步,设计走查零沟通成本。

  2. 如何支持多主题包
    把每个主题打成独立 CSS 文件,利用 Storybook 的 globalTypes 提供下拉选主题,story 里动态 import('./theme/dark.css'),实现 “一套代码,多套品牌”。

  3. 如何加自动化测试
    用 @storybook/test-runner 截图比对:切换主题前后对 .color-primary 色块取色值,断言色差 ΔE ≤ 2,防止 视觉回归。

  4. 如何开放给下游业务
    把变量包发布成 @company/design-tokens,并在 story 里导出 useCssVariables 钩子,业务方直接 import { useCssVariables } from '@company/design-tokens/storybook',文档即 SDK,大幅提升复用率。