SugarSS 缩进语法出错时,如何定位原始缩进行号?

解读

在国内前端团队的日常面试里,Stylelint 已经不只是“跑个 lint”那么简单,面试官更在意候选人能否在“非标准”语法(SugarSS、Sass、Less)出错时,把错误精准映射回源码位置,方便 CI 日志、VS Code 问题面板、GitHub Annotation 一键跳转。SugarSS 用缩进代替大括号,PostCSS 解析后生成的 AST 节点只记录“编译后”的行列号;一旦规则报错,默认指到转换后的 CSS 行号,开发者看到的是“第 42 行”,但源码里根本没有第 42 行,定位失败。能否把 PostCSS 的 source map 机制与 Stylelint 的 context 打通,是这道题的核心考点。

知识点

  1. PostCSS 的 node.source 对象:每个 AST 节点自带 input、start、end,input.from 指向原始文件路径,input.css 保留原始缩进文本。
  2. Stylelint 的 postcssResult:在插件上下文里可通过 ruleNode.source 拿到上述信息;stylelint.utils.report() 支持传入 line、column 覆盖默认行列。
  3. SugarSS 的 map: true:开启内联 source map 后,PostCSS 会把原始行号写进 node.source.start.line,无需额外 loader。
  4. Stylelint 自定义规则模板:
    const stylelint = require('stylelint');
    const ruleName = 'plugin/sugarss-indent';
    const messages = stylelint.utils.ruleMessages(ruleName, {
      rejected: 'SugarSS 缩进不一致'
    });
    module.exports = stylelint.createPlugin(ruleName, (primaryOption) => {
      return (root, result) => {
        root.walkDecls(decl => {
          const sourceLine = decl.source.start.line; // 原始行号
          if (/* 检测到缩进错误 */) {
            stylelint.utils.report({
              message: messages.rejected,
              node: decl,
              line: sourceLine, // 关键:显式指定原始行号
              result,
              ruleName
            });
          }
        });
      };
    });
    
  5. VS Code 集成:在 .vscode/settings.json 里把 "stylelint.validate": ["sugarss"] 打开,配合 postcss-language-support 插件,错误行号可直接跳转。
  6. CI 场景:GitHub Actions 中把 stylelint --formatter github 与 map: true 一起使用,Annotation 会显示原始 SugarSS 行号,不会误导开发者去改编译后的 CSS。

答案

在自定义规则里直接读取 node.source.start.line,把它作为 line 参数传给 stylelint.utils.report() 即可。
完整步骤:

  1. 配置 PostCSS 解析器为 sugarss 并开启 map: true;
  2. 在 Stylelint 插件中遍历 AST,发现缩进错误时,用 decl.source.start.line 拿到原始行号;
  3. 调用 stylelint.utils.report({ line: originalLine, ... }),Stylelint 会把该行号输出到终端、VS Code 问题面板及 CI Annotation,实现“报错即定位到原始缩进行”。

拓展思考

  1. 如果项目用 gulp-postcss 或 vite,source map 已被链式传递,只需保证 stylelint postcss-plugin 在管道最末端,无需重复生成 map。
  2. 对于 Less/Sass 的嵌套报错,思路相同,但需注意 node.source.input.from 可能是 .less 或 .scss,而 node.source.start.line 仍是原始行号,可直接复用。
  3. 大型 monorepo 中,子包路径深度不一,可在 report() 里同时传入 url: filepath,让 VS Code 的“问题”窗口支持 Ctrl+点击跳转。
  4. 若需把错误行号同步到钉钉/飞书机器人,可在自定义 formatter 里读取 warning.line,拼出 https://github.com/org/repo/blob/commit/path/to/file.sss#L{line} 的永久链接,实现“一键到行”的远程调试体验。