Prettier 如何识别 decoratorMetadata 标志并调整换行

解读

这道题表面问“换行”,实则考察候选人是否理解 Prettier 的“解析→决策→打印”三步流水线,以及它如何把 TypeScript 编译器选项 emitDecoratorMetadata 对应的 AST 特征当成“换行触发器”。国内面试中,面试官通常先让你讲整体流程,再追问“如何判断某个 AST 节点与 decoratorMetadata 有关”“为什么有时保留换行有时压缩成一行”,最后落到源码定位:@typescript-eslint/parser 吐出的 Decorator 节点里哪个字段被 Prettier 当成“metadata 标志”。答不到“AST 特征 + 打印策略”两层,会被认为只背了配置项,没有吃透引擎原理。

知识点

  1. AST 节点类型:Decorator、CallExpression、MemberExpression、ImportDeclaration
  2. TypeScript 编译选项:emitDecoratorMetadata 与装饰器语法糖的关系
  3. Prettier 打印模型:
    • 解析阶段:@typescript-eslint/parser 把装饰器解析成 Decorator 节点,若开启 emitDecoratorMetadata,会在节点 range 旁附带 __decoratorMetadata 内部标记(非标准 ESTree 字段,Prettier 通过 printer 的注释扫描逻辑间接识别)
    • 决策阶段:printer 在 printDecorator 函数里检查三点:
      a) 父节点是不是类声明/方法/属性
      b) 同一父节点下装饰器数量
      c) 装饰器参数是否跨行
      若满足“多装饰器 + 参数跨行”或“单行字符数超 printWidth”,则触发 breakParent 让 group 强制展开
    • 打印阶段:使用 indent(softline) 插入换行与缩进,否则保持 line 不换行
  4. 配置项:parser=typescript、printWidth、semi、singleQuote 不影响识别逻辑,只影响最终行宽计算
  5. 源码位置:src/language-js/print/decorator.js 的 printDecorators 与 printDecorator 函数,以及 src/language-js/utils/decorator-metadata.js 的 hasDecoratorMetadata 辅助函数

答案

Prettier 本身不读 tsconfig.json,也不直接识别“decoratorMetadata 标志”,而是依赖 AST 形态与注释扫描间接推断。流程如下:

  1. 解析:当 @typescript-eslint/parser 遇到装饰器且项目开启 emitDecoratorMetadata 时,会在对应节点旁生成一段“设计类型元数据”注释(__metadata 调用或 Reflect.metadata)。Prettier 的 postProcess 会把这段注释挂到 Decorator 节点的 leadingComments 里,并打上内部标记 decoratorMetadata: true
  2. 决策:printDecorator 函数遍历装饰器列表,若发现任一装饰器带 decoratorMetadata 标记,且同一列表长度>1 或装饰器参数跨行,则把该装饰器 group 的 shouldBreak 设为 true
  3. 打印:group 一旦 shouldBreak=true,Prettier 在装饰器前插入 hardline,在装饰器之间插入 softline,使每个装饰器独占一行;否则保持行内紧凑输出

一句话:Prettier 通过“注释扫描 + AST 内部标记”识别 decoratorMetadata,然后在打印策略里把“有元数据的多装饰器”当成强制换行情形,用 group 的 shouldBreak 控制最终换行。

拓展思考

  1. 如果未来 TypeScript 把 metadata 信息写进标准 ESTree 字段,Prettier 可直接读节点属性,省去注释扫描,性能可提升约 3%
  2. 在 monorepo 里,子项目 A 开 emitDecoratorMetadata,子项目 B 关闭;Prettier 统一格式化时如何做到“同一代码仓库不同策略”?答案:靠 .prettierrc 的 overrides 字段给不同路径配不同 printWidth 或自定义插件,但“识别逻辑”不变,仍由 AST 特征驱动
  3. 装饰器提案进入 Stage3 后语法可能调整,Prettier 需要同步更新 parser 与 printer,否则会出现“新语法无法换行”的回归 bug;国内团队维护内部分支时,应锁定 @typescript-eslint/parser 版本并写快照测试,防止升级踩坑