在 Storybook 中通过 Google Fonts 的 variable font 实现字重滑杆

解读

面试官想考察三件事:

  1. 你是否理解 Storybook 的“交互式控件”机制(Controls/Args)
  2. 你是否能把 Google Fonts 的 variable font 技术(字重轴 wght 100-900)与前端样式动态绑定
  3. 你是否能在 中国网络环境下 优雅加载外网字体(合规、可访问、性能可控),并把整个链路封装成可复用的 Story,让设计、产品、测试都能“拖一下滑杆就看效果”

知识点

  • Storybook Args & Controls:用 argTypes 把 number 类型的字重映射成 range slider,并设置 min/max/step
  • Google Fonts v2 API:请求 variable font 时带上 &display=swap 与 wght@100..900 范围,浏览器一次下载全轴文件
  • CSS font-variation-settings:真正生效的属性是 'wght' 轴,而不是传统 font-weight
  • 加载策略:国内项目建议把字体文件 托管到可备案的 CDN 或 本地 public 目录,避免 fonts.googleapis.com 被墙或延迟过高
  • Story 封装技巧:把字体加载逻辑写在 decorator 里,确保所有字重 story 共用同一份字体文件,避免重复请求
  • 性能与缓存:利用 rel="preconnect" 与 font-display: optional 做回退,减少阻塞渲染
  • 可访问性:滑杆要同步回显当前字重数值,并给 aria-valuetext 供屏幕阅读器识别

答案

  1. 准备字体
    国内线上环境,先把 https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap 下载成静态 CSS 与 woff2 文件,放到 public/fonts/inter/ 并配置 CORS 可缓存一年

  2. 写全局装饰器 .storybook/preview.js

    import { withVariableFont } from '../src/utils/withVariableFont';
    export const decorators = [withVariableFont];
    

    withVariableFont 会在 <head> 插入

    <link rel="preload" href="/fonts/inter/inter-var.woff2" as="font" type="font/woff2" crossorigin>
    <style>
      @font-face {
        font-family: 'InterVar';
        src: url('/fonts/inter/inter-var.woff2') format('woff2-variations');
        font-display: swap;
        font-weight: 100 900;
      }
    </style>
    
  3. 定义 Story

    // Typography.stories.jsx
    export default {
      title: 'Foundation/Typography',
      component: TextDemo,
      argTypes: {
        wght: {
          control: { type: 'range', min: 100, max: 900, step: 10 },
          description: '字重轴 wght',
        },
      },
    };
    
    const Template = (args) => (
      <p style={{
        fontFamily: 'InterVar, sans-serif',
        fontVariationSettings: `'wght' ${args.wght}`,
        fontSize: '48px',
      }}>
        可变字重演示:{args.wght}
      </p>
    );
    
    export const WeightSlider = Template.bind({});
    WeightSlider.args = { wght: 400 };
    
  4. 运行 npm run storybook
    打开 Controls 面板即可看到 字重滑杆,拖动后组件实时重渲染,URL 也随 args 同步,方便设计师把链接直接贴给开发

  5. 交付与文档
    在 DocsPage 里用 <Story id="foundation-typography--weight-slider" /> 嵌入,自动生成交互演示,零额外截图成本

拓展思考

  • 如果产品需要 斜体轴 slnt 或 宽度轴 wdth,只需在 argTypes 再新增两个 range,并把 font-variation-settings 拼成字符串模板;Storybook 会自动把多轴组合成矩阵,供 QA 一次性回归所有字形状态
  • 对于 暗黑模式,可把颜色也做成 Controls,结合 useDarkMode 插件,实现“字重+颜色”二维滑杆,验证可读性
  • 在 CI 阶段 用 chromatic 做视觉回归:每次 push 让机器人把 100~900 字重各截一张图,防止意外回退
  • 若项目需 离线运行(政企内网),把字体文件打进 Docker 镜像,Storybook 构建时走 staticDirs: ['../public'],保证内网也能无翻墙演示
  • 最后,把该 Story 导出为 MDX 文档,配上设计 token 表格(非 HTML 表格,用描述列表),即可成为团队 单一事实来源,实现真正的“组件即文档”