ESLint自定义规则怎么获取AST节点的父级信息?

公孙江梅 阅读 11

我正在写一个ESLint插件,想在遍历AST时拿到当前节点的父节点,但不知道怎么取。

试过在visitor里直接用node.parent,但有时候是undefined,是不是得先开启什么配置?

module.exports = {
  create(context) {
    return {
      Identifier(node) {
        // 这里想访问 node.parent,但经常是 undefined
        console.log(node.parent);
      }
    };
  }
};
我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
长孙怡瑶
试试这个方法。ESLint 的 AST 节点默认情况下是没有 parent 属性的,所以你需要手动给每个节点添加 parent 引用。你可以通过 eslint-scope 或者 eslint-utils 来处理,但最简单的方法是在遍历 AST 之前先构建 parent 映射。ESLint 提供了一个工具 eslint-visitor-keys 可以帮助你做这件事。

首先,安装 eslint-visitor-keys

npm install eslint-visitor-keys --save-dev


然后,在你的插件里这样用:

const visitorKeys = require('eslint-visitor-keys');

module.exports = {
create(context) {
const sourceCode = context.getSourceCode();
const ast = sourceCode.ast;

// 构建 parent 映射
function traverse(node, parent) {
if (node && typeof node === 'object') {
node.parent = parent;
visitorKeys.unionWith(node.type).forEach(key => {
if (Array.isArray(node[key])) {
node[key].forEach(child => traverse(child, node));
} else if (node[key] && typeof node[key].type === 'string') {
traverse(node[key], node);
}
});
}
}

traverse(ast, null);

return {
Identifier(node) {
// 现在可以访问 node.parent 了
console.log(node.parent);
}
};
}
};


这样,当你遍历 AST 的时候,每个节点都会有一个 parent 属性指向它的父节点,就不会再出现 undefined 的情况了。希望这能帮到你。
点赞
2026-03-25 00:02