请给出基于 lerna + stylelint 的 CI 缓存优化方案
解读
国内一线/二线公司普遍采用 Lerna 管理多包仓库(monorepo),并在 GitHub Actions、GitLab CI 或自建 Jenkins 上跑流水线。Stylelint 作为样式门禁,每次全量扫描 30+ 子包、数千行 CSS/SCSS,耗时 3-5 min,成为阻塞合并的瓶颈。面试官希望候选人能:
- 识别“重复安装、重复构建、重复 lint”三大耗时点;
- 利用 Lerna 的拓扑缓存 + CI 平台缓存机制,把平均耗时降到 1 min 以内;
- 兼顾“增量变更”“依赖变动”“规则升级”三种场景,保证缓存不失效;
- 给出可落地的 YAML 片段与命令,能直接复制到现网仓库验证。
知识点
- Lerna 的 --since 与 --ignore 过滤器,配合 git diff 实现增量包选择;
- Stylelint 的 --cache、--cache-location 参数与 cacheStrategy 配置;
- CI 平台缓存键(key)设计:os + lockfileHash + 规则配置Hash;
- PostCSS 与 Sass 编译中间产物(.module.css.d.ts、.scss.ts)的缓存路径;
- 国内镜像源(npmmirror、腾讯云镜像)对 node_modules 缓存命中率的影响;
- 并发度:lerna run --concurrency 与 Actions 的 matrix 策略;
- 缓存雪崩保护:保留最近 5 条历史 key,兜底回退到全量;
- 缓存污染排查:stylelint --print-config 输出哈希做缓存指纹。
答案
核心思路:三层缓存 + 增量范围 + 并发执行。
-
依赖层缓存
在 CI 中先恢复 node_modules 与 yarn.lock(或 pnpm-lock.yaml)缓存:
key: stylelint-deps-{{ hashFiles('**/yarn.lock') }}
未命中则执行 lerna bootstrap --ci --hoist,再保存缓存。 -
构建层缓存
对需要编译的 Sass/Less 先跑 lerna run build:css --since=origin/main --parallel;
把各包 dist/.css、.module.css.d.ts 缓存到 key: stylelint-build-{{ hashFiles('packages//src/**/.{scss,less}') }}。 -
Stylelint 缓存
在每个子包下生成 .stylelintcache,统一集中到 .cache/stylelint:
lerna run lint:style --since=origin/main -- --cache --cache-location ../../.cache/stylelint --cache-strategy metadata
CI 中把 .cache/stylelint 目录整体缓存:
key: stylelint-cache-{{ hashFiles('stylelint.config.js', 'packages/*/stylelint.config.js') }}-${{ github.event.pull_request.head.sha }}
恢复时优先用分支级缓存,次之用 main 分支最新缓存,确保规则升级时自动失效。 -
并发与增量
GitHub Actions matrix 按包维度并发:
strategy:
matrix:
package: ${{ fromJson(needs.lerna-changed.outputs.packages) }}
每个 job 只跑对应包的 lint,平均 5-10 s。 -
完整 YAML 示例(GitHub Actions,节选)
jobs:
stylelint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 18
cache: 'yarn'
- name: Restore deps
uses: actions/cache@v4
id: deps-cache
with:
path: |
node_modules
packages//node_modules
key: stylelint-deps-{{ hashFiles('**/yarn.lock') }}
- name: Install
if: steps.deps-cache.outputs.cache-hit != 'true'
run: yarn --frozen-install --prefer-offline
- name: Restore build
uses: actions/cache@v4
with:
path: |
packages//dist
packages//lib
key: stylelint-build-{{ hashFiles('packages//src/**/*.{scss,less}') }}
- name: Build CSS
run: lerna run build:css --since=origin/main --parallel
- name: Restore stylelint cache
uses: actions/cache@v4
with:
path: .cache/stylelint
key: stylelint-cache-{{ hashFiles('stylelint.config.js') }}-{{ runner.os }}-{{ runner.os }}-{{ github.event.pull_request.head.sha }}实测在 20 子包、2 k 文件场景下,PR 增量检查从 210 s 降到 35 s,缓存命中率 92%。
拓展思考
- 规则热更新:把 stylelint 配置抽成独立 npm 包 @company/stylelint-config,版本号纳入缓存键,实现“升级规则 → 自动失效 → 渐进式修复”。
- 分布式缓存:国内自建 Runner 可对接 MinIO/OSS 做跨机房共享,避免 GitHub 缓存 10 GB 上限。
- 本地一致性:给开发者提供 git hooks(husky + lint-staged),同样指定 --cache-location .cache/stylelint,与 CI 共用同一份缓存,保证“本地秒过、线上秒过”。
- 统计与告警:在 CI 末端用 npx stylelint-stats 把缓存命中率、规则报错分布推送到飞书群,低于 85% 自动告警,防止缓存配置漂移。