我正在为插件编写 ESLint 规则。我有以下测试代码:
const test = require('./test');
module.exports.foo = class Foo {}
module.exports.test = class Test {}
我有以下规则:
module.exports = {
create: (context) => ({
CallExpression: (node) => {
// The callee must be `require`.
if (node.callee.name !== 'require') {
return;
}
// Must be part of a VariableDeclarator.
if (node.parent.type !== 'VariableDeclarator') {
return;
}
const variable = node.parent.id;
if (variable.type !== 'Identifier') {
return;
}
// Now that we have the variable part of the expression `const name =
// require('name');`, find any identifiers in the code where the
// uppercased version of the `variable` is used.
}
})
}
正如您所看到的,在 CallExpression
中,我找到 require('./test');
来获取 test
变量名。然后,正如上面代码中的最后注释所示,我想要做的是找到名为 Test
的类。我不知道该怎么做。我尝试了以下方法,但不起作用:
const scope = context.getScope();
const capitalizedName = variable.name.charAt(0).toUpperCase() + variable.name.slice(1);
// `undefined` is returned. Why? Shouldn't it find the `Test` class, even if it's exported?
const classVariable = scope.variables.find(variable => variable.name === capitalizedName)
if (!classVariable) {
return;
}
const foundClassVariable = classVariable.references.find(({ identifier }) =>
['ClassDeclaration', 'ClassExpression'].includes(identifier.parent.type),
);
但它适用于以下测试代码(当类未导出时):
const test = require('./test');
class Test {}
有人知道我怎样才能让它工作吗?问题是否可能出在我正在使用的范围上,如果是这样,我如何获取文档根目录中定义的所有标识符,以搜索所有标识符?
最佳答案
这就是我最终所做的:
const scope = context.getScope();
const capitalizedName = variable.name.charAt(0).toUpperCase() + variable.name.slice(1);
const hasFoundClassVariable = scope.childScopes.some(childScope => childScope.type === 'class' && childScope.variables[0].name === capitalizedName)
guide here正如您所想象的那样,确实有帮助,因为它是官方文档。
关于javascript - 编写 ESLint 规则,如何通过标识符查找导出类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333552/