基于 AST 自动插入 rtl:ignore 注释

解读

“自动插入 rtl:ignore 注释”是国际化(i18n)场景下的高频诉求:

  1. 国内业务出海时,阿拉伯语、希伯来语等 RTL(Right-to-Left)布局需要把 CSS 中的方向性属性(margin-left、padding-right、left、right …)做自动翻转;
  2. 但部分 DOM 节点或样式片段必须强制保持 LTR,此时需要在源码里手工写 /* rtl:ignore */ 注释,告诉 postcss-rtl、rtlcss 等后处理工具“跳过翻转”;
  3. 手工加注释容易遗漏、代码 review 成本高,因此希望用 Babel 在编译阶段扫描 AST,对“符合某类特征”的 JSX 元素 / 模板字符串 / 对象属性自动插入该注释,实现“零感知”治理。

面试时,面试官想确认:

  • 你是否真的写过 Babel 插件,而不是只会调 preset;
  • 对 AST 节点类型、path 作用域、注释附着机制是否熟悉;
  • 能否在“不破坏源码行列号”的前提下完成精准注入,保证 source-map 可用;
  • 是否了解国内典型 RTL 方案(antd-style、@alifd/next、rax 国际化等)的注释规范。

知识点

  1. Babel 插件基本结构:export default function({ types: t, template }) { return { visitor: { … } } }
  2. AST 注释两种形态:leadingComments(前置)、trailingComments(后置);Babel 内部用 CommentBlock/CommentLine 节点表示,需通过 path.addComment(type, text, prepend?) 或 t.addComment(node, type, text) 写入。
  3. 常见“需要忽略翻转”的代码特征:
    • JSXElement 上同时存在 style 属性且包含左右方向性键名;
    • 模板字符串里出现 direction: ltr / margin-left 等硬编码;
    • ObjectExpression 里出现 left/right、marginLeft/marginRight 字面量;
    • 变量名命中业务约定的“ltrOnly”前缀。
  4. 作用域与重复防护:同一节点可能被多个 visitor 访问,需用 node.__rtlIgnoreInserted 做标记,防止重复加注释。
  5. source-map 一致性:禁止直接拼接字符串,必须通过 AST 接口操作,保证 inputSourceMap 正确传递。
  6. 国内构建链路:基于 Webpack + babel-loader,插件需支持 cacheDirectory,因此插件本身不能有副作用(不能读写文件、不能依赖全局变量)。
  7. 注释规范:postcss-rtl 8.x 之后要求 /* rtl:ignore */ 必须写在“规则前一行”或“声明前一行”,因此需要 leadingComments;若写在行尾,部分工具链不识别。

答案

下面给出可直接落地的 Babel 插件最小可用实现(单文件),覆盖“JSX 元素 + style 对象字面量”场景,国内面试时手写 80% 以上即可满分。

// babel-plugin-auto-rtl-ignore.js
export default function({ types: t }) {
  // 工具:判断字符串是否为方向性 key
  const isDirectionalKey = key =>
    /^(margin|padding|border)(Left|Right)|left|right|direction$/i.test(key);

  // 工具:给节点加 leading /* rtl:ignore */
  function addRtlIgnore(path) {
    if (path.node.__rtlIgnoreInserted) return;
    t.addComment(path.node, 'leading', ' rtl:ignore ', false);
    path.node.__rtlIgnoreInserted = true;
  }

  return {
    name: 'auto-rtl-ignore',
    visitor: {
      // 场景1:JSX 元素上出现 style 属性
      JSXElement(path) {
        path.node.openingElement.attributes.forEach(attr => {
          if (
            t.isJSXAttribute(attr) &&
            t.isJSXIdentifier(attr.name, { name: 'style' }) &&
            t.isJSXExpressionContainer(attr.value)
          ) {
            const stylePath = path.get(`openingElement.attributes.${path.node.openingElement.attributes.indexOf(attr)}.value.expression`);
            if (t.isObjectExpression(stylePath.node)) {
              scanObjectExpr(stylePath);
            }
          }
        });
      },

      // 场景2:普通对象字面量赋给 style
      ObjectExpression(path) {
        const parent = path.parent;
        if (
          t.isVariableDeclarator(parent) &&
          t.isIdentifier(parent.id, { name: /style/i })
        ) {
          scanObjectExpr(path);
        }
      }
    }
  };

  // 扫描对象表达式内部是否出现方向性 key
  function scanObjectExpr(path) {
    let needIgnore = false;
    path.node.properties.forEach(prop => {
      if (
        t.isObjectProperty(prop) &&
        t.isIdentifier(prop.key) &&
        isDirectionalKey(prop.key.name)
      ) {
        needIgnore = true;
      }
    });
    if (needIgnore) {
      addRtlIgnore(path);
    }
  }
}

使用方式(babel.config.js):

module.exports = {
  presets: ['@babel/preset-react'],
  plugins: ['./babel-plugin-auto-rtl-ignore']
};

验证输入:

const Button = () => (
  <button
    style={{ marginLeft: 8, paddingRight: 4 }}
  >
    保存
  </button>
);

输出:

const Button = () => (
  <button
    /* rtl:ignore */
    style={{ marginLeft: 8, paddingRight: 4 }}
  >
    保存
  </button>
);

关键点解释:

  • 采用 t.addComment 保证注释被 Babel 内部序列化器识别,行列号不变;
  • 通过 __rtlIgnoreInserted 防止同一节点被重复加注;
  • 只扫描 ObjectExpression,不处理计算属性或 Spread,避免过度注入;
  • 插件无副作用,可安全开启 babel-loader cache。

拓展思考

  1. 性能与规模:
    大型 Monorepo 中,全量文件遍历可能增加 5%~8% 编译耗时。可结合“文件路径黑名单”或“缓存索引”做优化;也可在开发态只注入警告,生产态再真正写注释。

  2. 规则可配置化:
    把“方向性 key 正则”/“需要忽略的组件名”/“注释内容”做成插件参数,满足多团队差异。例如 antd 的 Row/Col 组件默认不翻转,需要额外识别组件名。

  3. 与 Stylelint 规则联动:
    国内团队常把“是否写 rtl:ignore”纳入 CR 规范。可以写一条 Stylelint 自定义规则:若检测到方向性属性且没有相邻的 rtl:ignore 注释,则报错;Babel 插件负责自动修复,形成闭环。

  4. 对 TypeScript 的支持:
    当代码是 TSX 时,AST 节点类型完全一致,插件无需改动;但若使用 vue-next 的 SFC,需要再走 @vue/compiler-sfc 的 AST,思路相同,visitor 入口不同。

  5. 未来方向:
    随着 CSS 的 direction 和 logical properties(margin-inline-start)普及,方向性硬编码会减少,rtl:ignore 需求可能下降;但存量项目庞大,自动化解案在 3~5 年内仍是国内出海团队的刚需。面试时可主动提及“后续计划做 codemod,把 marginLeft 批量改为 marginInlineStart,从根源消除翻转风险”,体现前瞻性。