workleap-chromatic-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Workleap Chromatic Best Practices

Workleap Chromatic最佳实践

Guide for auditing and updating repositories to follow Workleap's Chromatic best practices.
本指南用于审核并更新代码仓库,使其遵循Workleap的Chromatic最佳实践。

Audit Workflow

审核工作流

When asked to audit or update a repository for Chromatic best practices, follow these steps in order:
当需要审核或更新代码仓库以符合Chromatic最佳实践时,请按以下步骤依次执行:

Step 1: Locate Chromatic Configuration

步骤1:定位Chromatic配置

Search for existing Chromatic setup:
chromatic.config.json
.storybook/preview.ts
.storybook/preview.tsx
.github/workflows/*chromatic*.yml
.github/workflows/*storybook*.yml
package.json (scripts section)
If no Chromatic configuration exists, ask the user if they want to set it up.
搜索已有的Chromatic配置文件:
chromatic.config.json
.storybook/preview.ts
.storybook/preview.tsx
.github/workflows/*chromatic*.yml
.github/workflows/*storybook*.yml
package.json (scripts 章节)
如果不存在Chromatic配置,请询问用户是否需要进行配置。

Step 2: Audit and Fix Each Practice

步骤2:审核并修复各项实践

2.1 Check
untraced
Configuration (Optional)

2.1 检查
untraced
配置(可选)

Find:
chromatic.config.json
Optional configuration:
json
{
    "$schema": "https://www.chromatic.com/config-file.schema.json",
    "untraced": ["**/package.json"]
}
Trade-off: Adding
package.json
to
untraced
reduces snapshot costs but may cause missed visual regressions when updating NPM packages that include breaking visual changes (e.g., UI library updates like Hopper).
When to use
untraced
:
  • Projects where dependency updates rarely affect visuals
  • Teams that manually verify visual changes after dependency updates
When to avoid
untraced
:
  • Projects heavily dependent on UI libraries (Hopper, design systems)
  • When visual regression detection for dependency updates is critical
Action: Ask the user about their preference. If they want to reduce costs and accept the trade-off, add the
untraced
option. Otherwise, skip this optimization.
查找文件:
chromatic.config.json
可选配置:
json
{
    "$schema": "https://www.chromatic.com/config-file.schema.json",
    "untraced": ["**/package.json"]
}
权衡:
package.json
添加到
untraced
中可以降低快照成本,但当更新包含视觉破坏性变更的NPM包(如Hopper这类UI库更新)时,可能会错过视觉回归问题。
何时使用
untraced
  • 依赖更新很少影响视觉效果的项目
  • 会在依赖更新后手动验证视觉变更的团队
何时避免使用
untraced
  • 严重依赖UI库(Hopper、设计系统)的项目
  • 依赖更新的视觉回归检测至关重要的场景
操作: 询问用户的偏好。如果他们希望降低成本并接受此权衡,则添加
untraced
选项;否则,跳过此优化。

2.2 Audit Storybook Preview Imports

2.2 审核Storybook预览文件的导入

Find:
.storybook/preview.ts
or
.storybook/preview.tsx
Look for barrel file imports:
ts
// BAD - barrel file import triggers full build when ANY export changes
import { ThemeProvider, I18nProvider } from "@app/providers";
import { something } from "../src";
import { util } from "@app/utils";
Replace with direct imports:
ts
// GOOD - direct imports only trigger rebuilds for specific file changes
import { ThemeProvider } from "@app/providers/ThemeProvider";
import { I18nProvider } from "@app/providers/I18nProvider";
Detection patterns:
  • Imports from paths ending in
    /index
    (explicit or implicit)
  • Imports from package-level paths like
    @app/utils
    or
    ../src
  • Multiple named imports from a single module (often indicates barrel)
Action: Refactor to direct imports. If the direct path doesn't exist, note it as a recommendation.
查找文件:
.storybook/preview.ts
.storybook/preview.tsx
查找桶文件导入:
ts
// 不良示例 - 桶文件导入会在任何导出内容变更时触发完整构建
import { ThemeProvider, I18nProvider } from "@app/providers";
import { something } from "../src";
import { util } from "@app/utils";
替换为直接导入:
ts
// 良好示例 - 直接导入仅在特定文件变更时触发重构
import { ThemeProvider } from "@app/providers/ThemeProvider";
import { I18nProvider } from "@app/providers/I18nProvider";
检测模式:
  • 从以
    /index
    结尾的路径导入(显式或隐式)
  • 从包级路径导入,如
    @app/utils
    ../src
  • 从单个模块导入多个命名导出(通常表示桶文件)
操作: 重构为直接导入。如果直接路径不存在,则将其记录为建议项。

2.3 Check for Local Chromatic Usage

2.3 检查本地Chromatic使用情况

Find:
package.json
scripts section
Bad patterns:
json
{
  "scripts": {
    "chromatic": "chromatic",
    "test:visual": "chromatic --project-token=...",
    "storybook:test": "chromatic"
  }
}
Action: Remove or comment out local Chromatic scripts. Chromatic should only run from CI via pull requests, never locally.
Why: Running Chromatic locally triggers the entire visual test suite, wasting snapshots.
查找文件:
package.json
的scripts章节
不良模式:
json
{
  "scripts": {
    "chromatic": "chromatic",
    "test:visual": "chromatic --project-token=...",
    "storybook:test": "chromatic"
  }
}
操作: 移除或注释掉本地Chromatic脚本。Chromatic应仅通过拉取请求在CI中运行,绝不能在本地运行。
原因: 在本地运行Chromatic会触发整个视觉测试套件,浪费快照资源。

2.4 Check CI Workflow for Label-Based Triggering

2.4 检查CI工作流的标签触发机制

Find: GitHub Actions workflow files that run Chromatic
Required pattern:
yaml
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
    types:
      - opened
      - labeled
  workflow_dispatch:

jobs:
  chromatic:
    steps:
      - name: Early exit if "run chromatic" label is not present
        if: github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'run chromatic')
        run: |
          echo "No \"run chromatic\" label present. Skipping Chromatic workflow."
          exit 78
Bad patterns:
yaml
undefined
查找文件: 运行Chromatic的GitHub Actions工作流文件
要求的模式:
yaml
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
    types:
      - opened
      - labeled
  workflow_dispatch:

jobs:
  chromatic:
    steps:
      - name: 若未添加"run chromatic"标签则提前退出
        if: github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'run chromatic')
        run: |
          echo "No \"run chromatic\" label present. Skipping Chromatic workflow."
          exit 78
不良模式:
yaml
undefined

BAD - runs on every PR without label check

不良示例 - 无标签检查,会在每个PR上运行

on: pull_request:
jobs: chromatic: # No label check

**Action:** Add label-based conditional execution. The label name should be `run chromatic`.
on: pull_request:
jobs: chromatic: # 无标签检查

**操作:** 添加基于标签的条件执行逻辑,标签名称应为`run chromatic`。

2.5 Check CI Workflow for Required Flags

2.5 检查CI工作流的必填参数

Find: Chromatic action step in CI workflow
Required flags:
yaml
- name: Chromatic
  uses: chromaui/action@latest
  with:
    projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
    onlyChanged: true        # Enables TurboSnap
    exitOnceUploaded: true   # Faster CI, doesn't wait for build
    autoAcceptChanges: main  # Auto-accept on main branch
Check for:
  • onlyChanged: true
    - Required for TurboSnap
  • exitOnceUploaded: true
    - Recommended for faster CI
  • autoAcceptChanges: main
    - Recommended to auto-accept baseline on main
Action: Add missing flags to the Chromatic action.
查找文件: CI工作流中的Chromatic action步骤
必填参数:
yaml
- name: Chromatic
  uses: chromaui/action@latest
  with:
    projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
    onlyChanged: true        # 启用TurboSnap
    exitOnceUploaded: true   # 加速CI,无需等待构建完成
    autoAcceptChanges: main  # 在main分支自动接受基线
检查项:
  • onlyChanged: true
    - 启用TurboSnap的必填项
  • exitOnceUploaded: true
    - 推荐用于加速CI
  • autoAcceptChanges: main
    - 推荐用于在main分支自动接受基线
操作: 为Chromatic action添加缺失的参数。

2.6 Check CI Workflow for Proper Git Checkout

2.6 检查CI工作流的Git checkout配置

Find: Checkout step in CI workflow
Required configuration:
yaml
- name: Checkout
  uses: actions/checkout@v6
  with:
    fetch-depth: 0  # Required for TurboSnap
    ref: ${{ github.event.pull_request.head.ref }}
  env:
    CHROMATIC_BRANCH: ${{ github.event.pull_request.head.ref || github.ref_name }}
    CHROMATIC_SHA: ${{ github.event.pull_request.head.sha || github.ref }}
    CHROMATIC_SLUG: ${{ github.repository }}
Critical check:
fetch-depth: 0
is required for TurboSnap to work properly.
Action: Add
fetch-depth: 0
and Chromatic environment variables if missing.
查找文件: CI工作流中的checkout步骤
必填配置:
yaml
- name: Checkout
  uses: actions/checkout@v6
  with:
    fetch-depth: 0  # TurboSnap正常工作的必填项
    ref: ${{ github.event.pull_request.head.ref }}
  env:
    CHROMATIC_BRANCH: ${{ github.event.pull_request.head.ref || github.ref_name }}
    CHROMATIC_SHA: ${{ github.event.pull_request.head.sha || github.ref }}
    CHROMATIC_SLUG: ${{ github.repository }}
关键检查:
fetch-depth: 0
是TurboSnap正常工作的必填项。
操作: 添加
fetch-depth: 0
和缺失的Chromatic环境变量。

2.7 Check Browser Configuration

2.7 检查浏览器配置

Find: Chromatic CLI flags in CI workflow or
chromatic.config.json
Look for multi-browser flags:
yaml
undefined
查找文件: CI工作流或
chromatic.config.json
中的Chromatic CLI参数
查找多浏览器参数:
yaml
undefined

BAD - doubles/triples snapshot count

不良示例 - 会使快照数量翻倍/三倍

npx chromatic --browsers chrome,firefox

**Required:** Chrome only (default, no flag needed)

**Action:** Remove multi-browser flags unless explicitly required.
npx chromatic --browsers chrome,firefox

**要求:** 仅使用Chrome(默认配置,无需添加参数)

**操作:** 移除多浏览器参数,除非有明确需求。

2.8 Check for Renovate/Changesets Exclusion

2.8 检查Renovate/Changesets的排除配置

Find: CI workflow and branch ruleset configuration
Recommendation: Exclude Renovate bot and Changesets branches from the required status check ruleset, not from the workflow itself.
Action: Document recommendation to configure branch ruleset to exclude:
  • renovate/*
    branches
  • changeset-release/*
    branches
查找文件: CI工作流和分支规则集配置
建议: 在必填状态检查规则集中排除Renovate机器人和Changesets分支,而非在工作流本身中排除。
操作: 记录配置建议,在分支规则集中排除以下分支:
  • renovate/*
    分支
  • changeset-release/*
    分支

2.9 Identify Large Files in Preview Dependencies

2.9 识别预览依赖中的大文件

Scan files imported by
.storybook/preview.ts[x]
for problematic patterns:
Problematic file types:
  • Localization files (
    **/resources.json
    ,
    **/translations/*.json
    )
  • Route definitions (large route config objects)
  • Environment configs
  • Utility files with many exports
Detection: Files with >20 exports or >500 lines that are imported by preview.
Action: Document findings and recommend splitting into smaller, focused modules.
扫描
.storybook/preview.ts[x]
导入的文件
,查找有问题的模式:
有问题的文件类型:
  • 本地化文件(
    **/resources.json
    ,
    **/translations/*.json
  • 路由定义(大型路由配置对象)
  • 环境配置
  • 包含大量导出的工具文件
检测标准: 被预览文件导入的、包含超过20个导出或超过500行代码的文件。
操作: 记录发现的问题,并建议将其拆分为更小的、聚焦的模块。

2.10 Check for Workflow Optimizations

2.10 检查工作流优化

Find: CI workflow file
Recommended patterns:
yaml
undefined
查找文件: CI工作流文件
推荐模式:
yaml
undefined

Concurrency to cancel in-progress runs

并发配置,取消正在进行的运行

concurrency: group: chromatic-${{ github.ref }} cancel-in-progress: true
concurrency: group: chromatic-${{ github.ref }} cancel-in-progress: true

Label removal after completion

完成后自动移除标签

  • name: Remove "run chromatic" label after Chromatic completion if: github.event_name == 'pull_request' uses: actions/github-script@v8 with: script: | github.rest.issues.removeLabel({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, name: 'run chromatic' });

**Action:** Add concurrency settings and label removal step if missing.
  • name: Chromatic完成后移除"run chromatic"标签 if: github.event_name == 'pull_request' uses: actions/github-script@v8 with: script: | github.rest.issues.removeLabel({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, name: 'run chromatic' });

**操作:** 添加并发配置和标签移除步骤(如果缺失)。

Step 3: Generate Audit Report

步骤3:生成审核报告

After completing the audit, provide a summary:
markdown
undefined
完成审核后,提供如下总结:
markdown
undefined

Chromatic Best Practices Audit

Chromatic最佳实践审核

Findings

发现

PracticeStatusAction Required
untraced
config (optional)
✅/❌/N/A[action or user declined]
Preview barrel imports✅/❌[action]
No local Chromatic scripts✅/❌[action]
CI label-based triggering✅/❌[action]
CI
onlyChanged: true
flag
✅/❌[action]
CI
fetch-depth: 0
✅/❌[action]
CI Chromatic env vars✅/❌[action]
Chrome-only snapshots✅/❌[action]
CI concurrency settings✅/❌[action]
CI label auto-removal✅/❌[action]
Large file dependencies✅/❌[action]
实践项状态所需操作
untraced
配置(可选)
✅/❌/N/A[操作或用户已拒绝]
预览文件的桶文件导入✅/❌[操作]
无本地Chromatic脚本✅/❌[操作]
CI基于标签的触发✅/❌[操作]
CI
onlyChanged: true
参数
✅/❌[操作]
CI
fetch-depth: 0
配置
✅/❌[操作]
CI Chromatic环境变量✅/❌[操作]
仅Chrome快照✅/❌[操作]
CI并发配置✅/❌[操作]
CI标签自动移除✅/❌[操作]
大文件依赖✅/❌[操作]

Changes Made

已做出的变更

  • [list of files modified]
  • [修改的文件列表]

Recommendations

建议

  • [list of suggested improvements that require user decision]
  • Consider adding
    untraced
    for package.json (trade-off: may miss UI library regressions)
  • Configure branch ruleset to exclude Renovate/Changesets branches
  • Add
    run chromatic
    as a required status check
undefined
  • [需要用户决策的改进建议列表]
  • 考虑为package.json添加
    untraced
    (权衡:可能会错过UI库的回归问题)
  • 配置分支规则集以排除Renovate/Changesets分支
  • run chromatic
    设为必填状态检查
undefined

Reference: Why These Practices Matter

参考:这些实践的重要性

TurboSnap Preservation

TurboSnap的保留

TurboSnap analyzes Git changes to snapshot only affected stories. These patterns disable TurboSnap and trigger full builds (all stories):
Change TypeFiles
Storybook preview
.storybook/preview.ts[x]
Barrel file dependenciesAny
index.ts[x]
imported by preview
Package dependencies
**/package.json
(optionally use
untraced
)
Large shared filesRoutes, constants, localization
Shallow git cloneMissing
fetch-depth: 0
TurboSnap会分析Git变更,仅对受影响的故事生成快照。以下模式会禁用TurboSnap并触发完整构建(所有故事):
变更类型文件
Storybook预览文件
.storybook/preview.ts[x]
桶文件依赖任何被预览文件导入的
index.ts[x]
包依赖
**/package.json
(可选择使用
untraced
大型共享文件路由、常量、本地化文件
Git浅克隆缺失
fetch-depth: 0

Snapshot Cost Multipliers

快照成本乘数

ConfigurationSnapshots per Story
Chrome only1x
Chrome + Safari2x
Chrome + Safari + Firefox3x
配置每个故事的快照数量
仅Chrome1倍
Chrome + Safari2倍
Chrome + Safari + Firefox3倍

CI Trigger Strategy

CI触发策略

Running Chromatic on every PR commit wastes snapshots on work-in-progress:
  • Use
    run chromatic
    label to trigger workflow
  • Auto-remove label after completion
  • Make workflow a required status check to remind reviewers
在每个PR提交时运行Chromatic会在工作进展中浪费快照:
  • 使用
    run chromatic
    标签触发工作流
  • 完成后自动移除标签
  • 将工作流设为必填状态检查,以提醒评审人员

Monorepo-Specific Audit

单体仓库(Monorepo)专属审核

For Turborepo/monorepo projects, additional checks:
  1. Per-package Chromatic configs: Each package with Storybook should have its own
    chromatic.config.json
  2. Turborepo cache in CI: Workflow should restore/save Turborepo cache:
    yaml
    - name: Restore Turborepo cache
      uses: actions/cache/restore@v5
      with:
        key: ${{ runner.os }}-turbo-chromatic-${{ github.sha }}
        restore-keys: |
          ${{ runner.os }}-turbo-chromatic-
          ${{ runner.os }}-turbo-
        path: .turbo
  3. Module-level triggering: For modular architecture, configure CI to run Chromatic only for affected modules
对于Turborepo/单体仓库项目,需额外检查以下内容:
  1. 每个包的Chromatic配置: 每个包含Storybook的包都应有独立的
    chromatic.config.json
  2. CI中的Turborepo缓存: 工作流应恢复/保存Turborepo缓存:
    yaml
    - name: 恢复Turborepo缓存
      uses: actions/cache/restore@v5
      with:
        key: ${{ runner.os }}-turbo-chromatic-${{ github.sha }}
        restore-keys: |
          ${{ runner.os }}-turbo-chromatic-
          ${{ runner.os }}-turbo-
        path: .turbo
  3. 模块级触发: 对于模块化架构,配置CI仅为受影响的模块运行Chromatic

Critical Rules

关键规则

  1. Never invent Chromatic options - Only use documented configuration
  2. CI-only execution - Never recommend running Chromatic locally
  3. Preserve TurboSnap - Every recommendation should maintain TurboSnap effectiveness
  4. Cost awareness - Every snapshot counts toward monthly budget
  1. 不要自定义Chromatic选项 - 仅使用官方文档中的配置
  2. 仅在CI中执行 - 绝不推荐在本地运行Chromatic
  3. 保留TurboSnap - 所有建议都应维持TurboSnap的有效性
  4. 成本意识 - 每个快照都会计入月度预算