如何在 Percy 快照前自动运行 Stylelint 确保无低级错误?
解读
面试官真正想考察的是“把代码质量卡点前置到视觉回归链路”的工程化能力。Percy 负责“看起来对不对”,Stylelint 负责“写得对不对”。如果样式低级错误(如拼错属性、重复选择器、未使用变量)混进主干,Percy 会生成无效快照,浪费 CI 分钟数与评审人力。因此,必须让 Stylelint 在 Percy 截图之前以“阻塞式”方式运行,并给出可落地的国内工程方案,兼顾 GitHub、GitLab 与私有云场景。
知识点
- Percy 客户端调用链:percy snapshot 命令之前可插入任意 shell 脚本,这是天然钩子。
- Stylelint 退出码:CLI 默认以 2 表示发现错误,1 表示异常,0 表示干净;CI 可据此中断后续步骤。
- 国内镜像与缓存:淘宝源、pnpm 缓存、GitLab 依赖代理,可显著缩短安装时间。
- 增量扫描:使用 stylelint --cache --cache-strategy metadata 只校验有变动的样式文件,降低 80% 耗时。
- 双通道报告:控制台输出供开发即时查看,JUnit XML 上传至 CI 面板供测试归档。
- 自动修复:--fix 后若仍有无法自动修复的规则,需让 CI 失败并提示本地运行 pnpm stylelint:fix。
- 合并请求卡点:GitLab MR、GitHub PR 均支持“状态检查”,Stylelint 未通过时 Percy 无需跑。
- 私有云 Jenkins:Pipeline 语法需声明 post { failure { notifyWechat } },把错误截图推送到企业微信。
答案
- 在 package.json 定义质量脚本
"scripts": {
"lint:style": "stylelint '**/*.{css,scss,less}' --cache --cache-strategy metadata --max-warnings 0",
"lint:style:fix": "stylelint '**/*.{css,scss,less}' --fix"
}
--max-warnings 0 把警告也当错误,彻底杜绝低级问题。
- CI 阶段编排(GitHub Actions 示例,GitLab/Jenkins 同理)
name: Visual Regression
on:
pull_request:
paths: ['**/*.scss', '**/*.css', '**/*.less']
jobs:
style-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: actions/setup-node@v4
with:
node-version: 18
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- run: pnpm lint:style
- name: 上传报告
if: failure()
uses: actions/upload-artifact@v3
with:
name: stylelint-report
path: stylelint-report.xml
percy:
needs: style-check # 关键点:Percy 依赖 style-check 成功
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- run: pnpm install --frozen-lockfile
- run: pnpm build:storybook
- run: npx percy snapshot storybook-static
env:
PERCY_TOKEN: ${{ secrets.PERCY_TOKEN }}
若 style-check 失败,Percy 阶段不会执行,快照费用与评审时间双双节省。
-
本地提前拦截
安装 husky + lint-staged,在 commit 前自动执行 lint:style:fix;无法修复时阻断提交,保证进入远端的代码已经干净。 -
国内加速
在 .npmrc 写入
registry=https://registry.npmmirror.com
并在 CI 里缓存 ~/.local/share/pnpm/store,可把依赖安装耗时从 2 min 降到 20 s。
- 私有云场景
Jenkins Pipeline 中调用 sh 'pnpm lint:style',失败时 currentBuild.result = 'FAILURE',并在 post 里调用企业微信 API,把错误行号直接推送到群,实现“快照未跑,问题已定位”。
拓展思考
- 如果仓库同时存在 Tailwind CSS 与 SCSS,可把 stylelint-config-tailwindcss 与 stylelint-config-standard-scss 做深度合并,避免规则冲突。
- 对于微前端场景,主应用与多个子应用共用一条 Percy pipeline,可在 lint 阶段使用 stylelint-config-recess-order 做属性排序校验,保证不同团队产物合并后仍保持统一顺序,降低视觉差分噪声。
- 当样式文件超过 5 000 个,缓存仍不足以提速,可引入 nx affected:lint 或 turborepo,只让受影响的子包跑 Stylelint,进一步把检查时间压到 10 s 级,实现“秒级卡点、分钟级快照”。