workleap-chromatic-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWorkleap 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)
untraced2.1 检查untraced
配置(可选)
untracedFind:
chromatic.config.jsonOptional configuration:
json
{
"$schema": "https://www.chromatic.com/config-file.schema.json",
"untraced": ["**/package.json"]
}Trade-off: Adding to 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).
package.jsonuntracedWhen 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 option. Otherwise, skip this optimization.
untraced查找文件:
chromatic.config.json可选配置:
json
{
"$schema": "https://www.chromatic.com/config-file.schema.json",
"untraced": ["**/package.json"]
}权衡: 将添加到中可以降低快照成本,但当更新包含视觉破坏性变更的NPM包(如Hopper这类UI库更新)时,可能会错过视觉回归问题。
package.jsonuntraced何时使用:
untraced- 依赖更新很少影响视觉效果的项目
- 会在依赖更新后手动验证视觉变更的团队
何时避免使用:
untraced- 严重依赖UI库(Hopper、设计系统)的项目
- 依赖更新的视觉回归检测至关重要的场景
操作: 询问用户的偏好。如果他们希望降低成本并接受此权衡,则添加选项;否则,跳过此优化。
untraced2.2 Audit Storybook Preview Imports
2.2 审核Storybook预览文件的导入
Find: or
.storybook/preview.ts.storybook/preview.tsxLook 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 (explicit or implicit)
/index - Imports from package-level paths like or
@app/utils../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: scripts section
package.jsonBad 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.
查找文件: 的scripts章节
package.json不良模式:
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 78Bad 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
undefinedBAD - 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 branchCheck for:
- - Required for TurboSnap
onlyChanged: true - - Recommended for faster CI
exitOnceUploaded: true - - Recommended to auto-accept baseline on main
autoAcceptChanges: 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分支自动接受基线检查项:
- - 启用TurboSnap的必填项
onlyChanged: true - - 推荐用于加速CI
exitOnceUploaded: true - - 推荐用于在main分支自动接受基线
autoAcceptChanges: 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: is required for TurboSnap to work properly.
fetch-depth: 0Action: Add and Chromatic environment variables if missing.
fetch-depth: 0查找文件: 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 }}关键检查: 是TurboSnap正常工作的必填项。
fetch-depth: 0操作: 添加和缺失的Chromatic环境变量。
fetch-depth: 02.7 Check Browser Configuration
2.7 检查浏览器配置
Find: Chromatic CLI flags in CI workflow or
chromatic.config.jsonLook for multi-browser flags:
yaml
undefined查找文件: CI工作流或中的Chromatic CLI参数
chromatic.config.json查找多浏览器参数:
yaml
undefinedBAD - 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:
- branches
renovate/* - branches
changeset-release/*
查找文件: CI工作流和分支规则集配置
建议: 在必填状态检查规则集中排除Renovate机器人和Changesets分支,而非在工作流本身中排除。
操作: 记录配置建议,在分支规则集中排除以下分支:
- 分支
renovate/* - 分支
changeset-release/*
2.9 Identify Large Files in Preview Dependencies
2.9 识别预览依赖中的大文件
Scan files imported by for problematic patterns:
.storybook/preview.ts[x]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
undefinedConcurrency 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
undefinedChromatic Best Practices Audit
Chromatic最佳实践审核
Findings
发现
| Practice | Status | Action Required |
|---|---|---|
| ✅/❌/N/A | [action or user declined] |
| Preview barrel imports | ✅/❌ | [action] |
| No local Chromatic scripts | ✅/❌ | [action] |
| CI label-based triggering | ✅/❌ | [action] |
CI | ✅/❌ | [action] |
CI | ✅/❌ | [action] |
| CI Chromatic env vars | ✅/❌ | [action] |
| Chrome-only snapshots | ✅/❌ | [action] |
| CI concurrency settings | ✅/❌ | [action] |
| CI label auto-removal | ✅/❌ | [action] |
| Large file dependencies | ✅/❌ | [action] |
| 实践项 | 状态 | 所需操作 |
|---|---|---|
| ✅/❌/N/A | [操作或用户已拒绝] |
| 预览文件的桶文件导入 | ✅/❌ | [操作] |
| 无本地Chromatic脚本 | ✅/❌ | [操作] |
| CI基于标签的触发 | ✅/❌ | [操作] |
CI | ✅/❌ | [操作] |
CI | ✅/❌ | [操作] |
| CI Chromatic环境变量 | ✅/❌ | [操作] |
| 仅Chrome快照 | ✅/❌ | [操作] |
| CI并发配置 | ✅/❌ | [操作] |
| CI标签自动移除 | ✅/❌ | [操作] |
| 大文件依赖 | ✅/❌ | [操作] |
Changes Made
已做出的变更
- [list of files modified]
- [修改的文件列表]
Recommendations
建议
- [list of suggested improvements that require user decision]
- Consider adding for package.json (trade-off: may miss UI library regressions)
untraced - Configure branch ruleset to exclude Renovate/Changesets branches
- Add as a required status check
run chromatic
undefined- [需要用户决策的改进建议列表]
- 考虑为package.json添加(权衡:可能会错过UI库的回归问题)
untraced - 配置分支规则集以排除Renovate/Changesets分支
- 将设为必填状态检查
run chromatic
undefinedReference: 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 Type | Files |
|---|---|
| Storybook preview | |
| Barrel file dependencies | Any |
| Package dependencies | |
| Large shared files | Routes, constants, localization |
| Shallow git clone | Missing |
TurboSnap会分析Git变更,仅对受影响的故事生成快照。以下模式会禁用TurboSnap并触发完整构建(所有故事):
| 变更类型 | 文件 |
|---|---|
| Storybook预览文件 | |
| 桶文件依赖 | 任何被预览文件导入的 |
| 包依赖 | |
| 大型共享文件 | 路由、常量、本地化文件 |
| Git浅克隆 | 缺失 |
Snapshot Cost Multipliers
快照成本乘数
| Configuration | Snapshots per Story |
|---|---|
| Chrome only | 1x |
| Chrome + Safari | 2x |
| Chrome + Safari + Firefox | 3x |
| 配置 | 每个故事的快照数量 |
|---|---|
| 仅Chrome | 1倍 |
| Chrome + Safari | 2倍 |
| Chrome + Safari + Firefox | 3倍 |
CI Trigger Strategy
CI触发策略
Running Chromatic on every PR commit wastes snapshots on work-in-progress:
- Use label to trigger workflow
run chromatic - 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:
-
Per-package Chromatic configs: Each package with Storybook should have its own
chromatic.config.json -
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 -
Module-level triggering: For modular architecture, configure CI to run Chromatic only for affected modules
对于Turborepo/单体仓库项目,需额外检查以下内容:
-
每个包的Chromatic配置: 每个包含Storybook的包都应有独立的
chromatic.config.json -
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 -
模块级触发: 对于模块化架构,配置CI仅为受影响的模块运行Chromatic
Critical Rules
关键规则
- Never invent Chromatic options - Only use documented configuration
- CI-only execution - Never recommend running Chromatic locally
- Preserve TurboSnap - Every recommendation should maintain TurboSnap effectiveness
- Cost awareness - Every snapshot counts toward monthly budget
- 不要自定义Chromatic选项 - 仅使用官方文档中的配置
- 仅在CI中执行 - 绝不推荐在本地运行Chromatic
- 保留TurboSnap - 所有建议都应维持TurboSnap的有效性
- 成本意识 - 每个快照都会计入月度预算