SugarSS 缩进语法出错时,如何定位原始缩进行号?
解读
在国内前端团队的日常面试里,Stylelint 已经不只是“跑个 lint”那么简单,面试官更在意候选人能否在“非标准”语法(SugarSS、Sass、Less)出错时,把错误精准映射回源码位置,方便 CI 日志、VS Code 问题面板、GitHub Annotation 一键跳转。SugarSS 用缩进代替大括号,PostCSS 解析后生成的 AST 节点只记录“编译后”的行列号;一旦规则报错,默认指到转换后的 CSS 行号,开发者看到的是“第 42 行”,但源码里根本没有第 42 行,定位失败。能否把 PostCSS 的 source map 机制与 Stylelint 的 context 打通,是这道题的核心考点。
知识点
- PostCSS 的
node.source对象:每个 AST 节点自带input、start、end,input.from指向原始文件路径,input.css保留原始缩进文本。 - Stylelint 的
postcssResult:在插件上下文里可通过ruleNode.source拿到上述信息;stylelint.utils.report()支持传入line、column覆盖默认行列。 - SugarSS 的
map: true:开启内联 source map 后,PostCSS 会把原始行号写进node.source.start.line,无需额外 loader。 - 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 }); } }); }; }); - VS Code 集成:在
.vscode/settings.json里把"stylelint.validate": ["sugarss"]打开,配合postcss-language-support插件,错误行号可直接跳转。 - CI 场景:GitHub Actions 中把
stylelint --formatter github与map: true一起使用,Annotation 会显示原始 SugarSS 行号,不会误导开发者去改编译后的 CSS。
答案
在自定义规则里直接读取 node.source.start.line,把它作为 line 参数传给 stylelint.utils.report() 即可。
完整步骤:
- 配置 PostCSS 解析器为
sugarss并开启map: true; - 在 Stylelint 插件中遍历 AST,发现缩进错误时,用
decl.source.start.line拿到原始行号; - 调用
stylelint.utils.report({ line: originalLine, ... }),Stylelint 会把该行号输出到终端、VS Code 问题面板及 CI Annotation,实现“报错即定位到原始缩进行”。
拓展思考
- 如果项目用
gulp-postcss或vite,source map 已被链式传递,只需保证stylelint postcss-plugin在管道最末端,无需重复生成 map。 - 对于 Less/Sass 的嵌套报错,思路相同,但需注意
node.source.input.from可能是.less或.scss,而node.source.start.line仍是原始行号,可直接复用。 - 大型 monorepo 中,子包路径深度不一,可在
report()里同时传入url: filepath,让 VS Code 的“问题”窗口支持 Ctrl+点击跳转。 - 若需把错误行号同步到钉钉/飞书机器人,可在自定义 formatter 里读取
warning.line,拼出https://github.com/org/repo/blob/commit/path/to/file.sss#L{line}的永久链接,实现“一键到行”的远程调试体验。