如何在自定义 ESLint 规则中检测特定函数调用?

Mc.星语 阅读 16

我正在写一个 ESLint 自定义规则,想检测代码里有没有调用 dangerousFunction,但不知道怎么准确匹配 CallExpression。试了几次都没生效,规则好像没触发。

这是我的测试代码:

function test() {
  dangerousFunction('hello');
  safeFunction('world');
}
我来解答 赞 4 收藏
二维码
手机扫码查看
2 条解答
Zz舒昕
Zz舒昕 Lv1
当时我也卡在这,CallExpression 匹配不生效主要是因为没正确判断 callee 的类型。ESLint 里要匹配函数调用,得先确认是 CallExpression,再检查它的 callee 是不是 Identifier 且 name 是 'dangerousFunction'。

你规则里大概率是直接用了 CallExpression 就完事,但没过滤 callee,结果像 obj.dangerousFunction()importedFn() 这类情况就漏掉了。

正确的匹配方式是这样写:

module.exports = {
meta: {
type: 'problem',
docs: {
description: '禁止调用 dangerousFunction'
},
schema: []
},
create(context) {
return {
CallExpression(node) {
const callee = node.callee;
if (callee.type === 'Identifier' && callee.name === 'dangerousFunction') {
context.report({
node,
message: '禁止调用 dangerousFunction'
});
}
}
};
}
};


如果你还要支持 dangerousFunction() 是从模块导入的情况(比如 import { dangerousFunction } from 'xxx'),那得加额外逻辑判断 symbol,但基础场景上面这个就够了。我一开始就是漏了 callee.type === 'Identifier' 这步,一直以为 ESLint 没触发,其实规则跑得挺正常,只是条件太宽没匹配到。
点赞 3
2026-02-24 18:08
景景 ☘︎
懒人方案:直接匹配 CallExpression,然后判断 callee 的 name 是不是 "dangerousFunction",ESLint rule 里这么写就行:

module.exports = {
meta: { type: 'problem' },
create(context) {
return {
CallExpression(node) {
if (node.callee.type === 'Identifier' && node.callee.name === 'dangerousFunction') {
context.report({ node, message: '禁止调用 dangerousFunction' });
}
}
};
}
};
点赞 4
2026-02-23 23:04