如何为 Stylus 编写 customSyntax 并集成到 stylelint.config.js?

解读

  1. 国内前端团队普遍使用 Stylus 作为“零大括号”CSS 预处理器,但 Stylelint 官方只内置了 CSS/SCSS/Less 的 parser。
  2. 面试官想确认三件事:
    • 你是否理解 Stylelint 的“解析 → 构建 AST → 走查规则” 链路;
    • 能否把 Stylus 的 AST 映射成 PostCSS 兼容节点,让 170+ 条内置规则“零改造”生效;
    • 能否把自定义语法平滑接入 CI、VS Code、Webpack,而不破坏现有配置。
  3. 现场不会给你 2 小时写完整 parser,但要求你在 10 分钟内给出“最小可运行骨架 + 配置入口”,并解释边界 case(缩进敏感、无分号、混合、@block、hash、function call 等)。

知识点

  • PostCSS 的 Parser 接口:输入 → tokenizer → 生成 Root/Rule/Decl/Comment 节点。
  • Stylelint customSyntax 约定:导出一个函数,签名为 function(source, opts): Root,返回标准 PostCSS AST。
  • Stylus 官方暴露的 stylus.parse() 生成的是自研 AST(nodes.Block),需要二次遍历转成 PostCSS 节点;必须保留 source、raws、position 字段,否则行号报错。
  • 命名规范:包名必须带 stylelint- 前缀,发布到 npm 私仓或阿里源,方便团队统一拉取。
  • 配置优先级:stylelint.config.js 的 customSyntax 字段 > 行内 --custom-syntax CLI 参数 > 插件内部声明。
  • 性能陷阱:Stylus 允许“Python 式缩进”,token 阶段要缓存缩进栈,否则 O(n²) 回溯会让大文件 lint 时间飙到 3s+。
  • 自动修复:只需保证 AST 能被 stringifier 还原成合法 Stylus;stylefmt-stylus 已停止维护,因此 customSyntax 里最好同时暴露 stringify 方法,让 --fix 直接落地。
  • 与 stylelint-config-standard 混用:把会产生误报的规则(declaration-empty-line-before、number-leading-zero)在 overrides 里关掉,或写自定义规则做 Stylus 语法降级。

答案

步骤 1:初始化 custom-syntax 包

mkdir stylelint-stylus-syntax && cd $_
npm init -y
npm i -S stylus postcss@^8

步骤 2:编写主入口 lib/index.js

const stylus = require('stylus');
const { Root, Rule, Decl, Comment } = require('postcss');

function stylusParser(source, opts) {
  // 1. 用 stylus 官方 parser 生成自研 AST
  const ast = stylus.parse(source, { filename: opts.from });

  // 2. 创建 PostCSS Root
  const root = new Root({ source: { input: { css: source, file: opts.from }, start: { line: 1, column: 1 } } });

  // 3. 递归遍历 stylus AST 并映射
  function walk(node, parent) {
    if (node.nodeName === 'group') {
      // 选择器节点
      const rule = new Rule({
        selector: node.nodes.map(n => n.val || n.name).join(''),
        source: { start: { line: node.lineno, column: node.column }, input: root.source.input }
      });
      parent.append(rule);
      node.nodes.forEach(n => n.block && walk(n.block, rule));
    } else if (node.nodeName === 'ident' && node.val && node.val.nodeName === 'expression') {
      // 声明节点
      const decl = new Decl({
        prop: node.name,
        value: node.val.nodes.map(v => v.val || v.name).join(''),
        source: { start: { line: node.lineno, column: node.column }, input: root.source.input }
      });
      parent.append(decl);
    } else if (node.nodeName === 'comment') {
      parent.append(new Comment({ text: node.str, source: { start: { line: node.lineno, column: node.column }, input: root.source.input } }));
    } else if (node.nodes) {
      node.nodes.forEach(n => walk(n, parent));
    }
  }

  walk(ast, root);
  return root;
}

module.exports = stylusParser;

步骤 3:暴露 stringify(可选,但推荐)

const stylus = require('stylus');
module.exports.stringify = function(root, builder) {
  // 极简实现:直接拼字符串,生产环境可接入 stylus renderer
  root.walkDecls(decl => builder(`${decl.prop} ${decl.value}`, decl));
  root.walkRules(rule => builder(`${rule.selector} {\n`, rule));
};

步骤 4:在 stylelint.config.js 中集成

module.exports = {
  extends: ['stylelint-config-standard'],
  customSyntax: require.resolve('stylelint-stylus-syntax'),
  rules: {
    // 关闭与 stylus 缩进冲突的规则
    'declaration-empty-line-before': null,
    'number-leading-zero': null
  }
};

步骤 5:本地验证

npx stylelint "src/**/*.styl" --fix

若控制台无 parser error,且 VS Code 插件正常高亮,即集成成功。

拓展思考

  1. 混合(mixin)与 @block 在 AST 里会被解析为匿名节点,如何给它们生成伪 Rule 节点,使得 selector-max-id 这类规则依然可生效?
  2. Stylus 支持 hash object {bg: #000, color: #fff},映射到 PostCSS 时是否拆成多个 Decl?还是整体当成 function 表达式?不同策略会影响 property-no-unknown 的误报率。
  3. 生产环境需要 source-map 回跳原始 .styl 行号,customSyntax 里需在 Root#source 上附加 map: opts.from ? new PreviousMap(opts.from, opts.map) : null,否则 CI 报错无法定位。
  4. 如果团队把 Stylus 与 Vue SFC <style lang="styl"> 混用,可基于 @stylelint/postcss-css-in-js 再包一层,走 vue-eslint-parser 提取 <style> 区块,统一走上述 customSyntax,实现“单管道” lint。