如何在 PR 中自动运行 Stylelint 并上传报告?

解读

面试官真正想考察的是“把 Stylelint 无缝嵌入国内 Git 工作流”的完整闭环:

  1. 触发时机——PR 创建或更新时自动执行;
  2. 运行环境——选择国内可访问、速度稳定的 CI 服务(GitHub Actions 虽常用,但 Gitee、Coding、阿里云云效、腾讯云 CODING CI 才是多数国内企业的现实选择);
  3. 依赖安装——兼顾内网源、缓存、lock 文件一致性;
  4. 规则与忽略——如何确保规则文件、ignore 文件、共享配置在仓库内统一;
  5. 报告产出——既要让机器可读(exit code 阻断合并),又要让人可读(HTML/Markdown 报告、Annotations 直接定位到行);
  6. 结果回写——把报告以 Checks、Comment、Artifact 形式上传到 PR,实现“零跳转”即可看到错误截图;
  7. 失败策略——阻断合并还是仅警告,是否允许自动修复提交;
  8. 性能与成本——并行、增量、缓存,降低团队 CI 分钟数。

回答时务必给出“可直接落地的 YAML + 脚本”,并解释每一步为什么这么做,才能体现工程化深度。

知识点

  • 国内主流 CI 平台差异:GitHub Actions(国际项目)、Gitee Go(码云)、Coding CI(腾讯云)、阿里云云效、GitLab CI(自建)。
  • Stylelint CLI 核心参数:--formatter、--custom-formatter、--output-file、--max-warnings、--fix、--cache、--cache-location。
  • 自定义 formatter:官方 json、string、compact、unix、tap,社区有 stylelint-checkstyle-reporter、stylelint-junit-reporter、stylelint-html-formatter。
  • 报告上传三种形态:
    1. Checks API / MR Note:把错误行直接映射到 PR 文件 diff;
    2. Artifact:上传 html/json 供下载;
    3. Comment Bot:聚合后只发一条评论,避免刷屏。
  • 增量校验:git diff --name-only origin/base...HEAD∣grep−E′(˙css∣scss∣less){base}...HEAD | grep -E '\.(css|scss|less)' | xargs stylelint,减少全量扫描时间。
  • 缓存加速:stylelint --cache --cache-strategy metadata 配合 CI 缓存目录,二次构建秒级完成。
  • 自动修复:stylelint --fix 后判断 git diff --quiet;若有改动,机器人账号 commit 并 push,需配置 PAT 或 CI token 有写权限。
  • 阻断合并:CI job exit 1 即可;平台侧再配“必须通过检查”规则。
  • 私有 npm 源:国内公司常用 Verdaccio、cnpm、Nexus,CI 内写入 .npmrc 或环境变量 NPM_CONFIG_REGISTRY。

答案

以下示例基于“Gitee + Gitee Go”——国内私有仓库最常见场景,完整展示“PR 触发 → 增量扫描 → 生成 HTML 报告 → 回写 PR 评论 → 阻断合并”的闭环。GitHub Actions 仅需把触发关键字和上传命令替换即可,思路完全一致。

  1. 仓库根目录准备
    .stylelintrc.js
    module.exports = {
    extends: ['stylelint-config-standard-scss'],
    rules: { 'alpha-value-notation': null },
    ignoreFiles: ['dist//*', '/*.min.css']
    };

    .stylelintignore
    node_modules
    coverage

  2. Gitee Go 配置文件 gitee-go.yml
    name: PR Stylelint
    on:
    pull_request:
    types: [opened, synchronize]

    env:
    CACHE_DIR: .stylelint-cache

    jobs:
    lint:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    with:
    fetch-depth: 0 # 获取基线分支历史,用于增量 diff

      - name: Setup Node  
        uses: actions/setup-node@v3  
        with:  
          node-version: 18  
          cache: 'npm'  
    
      - name: Install deps  
        run: |  
          npm config set registry https://registry.npmmirror.com  
          npm ci  
    
      - name: Restore stylelint cache  
        uses: actions/cache@v3  
        with:  
          path: ${{ env.CACHE_DIR }}  
          key: stylelint-${{ runner.os }}-${{ hashFiles('**/*.scss', '**/*.css') }}  
    
      - name: Get changed styles  
        id: changed  
        run: |  
          echo "files=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.(css|scss|less)$' | xargs)" >> $GITHUB_OUTPUT  
    
      - name: Run Stylelint  
        if: steps.changed.outputs.files  
        run: |  
          mkdir -p reports  
          npx stylelint ${{ steps.changed.outputs.files }} \
            --formatter json --output-file reports/stylelint.json \
            --max-warnings 0 --cache --cache-location ${{ env.CACHE_DIR }} \
            --custom-formatter node_modules/stylelint-html-formatter/index.js > reports/stylelint.html  
    
      - name: Upload HTML report  
        uses: actions/upload-artifact@v3  
        with:  
          name: stylelint-report  
          path: reports/stylelint.html  
    
      - name: Comment PR  
        uses: actions/github-script@v6  
        if: always() && steps.changed.outputs.files  
        with:  
          script: |  
            const fs = require('fs');  
            const json = JSON.parse(fs.readFileSync('reports/stylelint.json','utf8'));  
            const total = json.reduce((a,r)=>a+r.warnings.length,0);  
            const body = total === 0  
              ? '✅ Stylelint 检测通过'  
              : `🚫 发现 **${total}** 处样式问题,[下载详细报告](https://gitee.com/${{ github.repository }}/actions/artifacts/${{ github.run_id }})。`;  
            github.rest.issues.createComment({  
              issue_number: context.issue.number,  
              owner: context.repo.owner,  
              repo: context.repo.repo,  
              body  
            });  
    
      - name: Fail if errors  
        if: steps.changed.outputs.files  
        run: |  
          errors=$(jq '.[] | .warnings | length' reports/stylelint.json | jq -s 'add')  
          if [[ $errors -gt 0 ]]; then exit 1; fi  
    
  3. 平台侧设置
    在 Gitee 仓库“设置-合并请求-合并限制”中勾选“必须通过 PR Stylelint 检查”,实现强制阻断。

  4. 自动修复(可选)
    新增 job fix:
    npx stylelint {{ steps.changed.outputs.files }} --fix git config user.name "ci-bot" git config user.email "ci-bot@company.com" git add . git diff --quiet && exit 0 git commit -m "style: auto fix by stylelint" git push origin HEAD:{{ github.head_ref }}

    注意给机器人账号配置“开发者”权限并写入 PAT。

拓展思考

  1. 多包仓库(Monorepo)如何拆分规则与缓存?
    可在每个子包放置 .stylelintrc,CI 里用 lerna/changesets 获取变更包,再逐包执行 stylelint --cache --cache-location node_modules/.cache/stylelint-${包名},避免跨包污染。

  2. 如何与 UI 走查工具联动?
    把 stylelint 报告解析成 allure 或 mochawesome 格式,统一上传到测试平台,与视觉回归、单元测试报告聚合,实现“一站式质量看板”。

  3. 规则治理如何持续?
    建立 stylelint-rules 私有包,把公司级配置、自定义插件、ignore 模板集中版本化管理;各业务线通过 extends 引用,规则升级只需改一处,CI 自动发版并触发依赖更新 PR。

  4. 增量扫描仍有误杀怎么办?
    可引入 stylelint-diff-prettier,结合 prettier 的 range 格式化能力,只对 diff hunks 中的行做校验,彻底解决“旧代码触雷”问题。