javascript - 编写 ESLint 规则,如何通过标识符查找导出类?

标签 javascript class eslint abstract-syntax-tree lint

我正在为插件编写 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/

相关文章:

javascript - SonarQube:在 SonarQube 中为 JavaScript 集成 ESLint?

javascript - 任何确定透明背景颜色CSS的方法

javascript - 如何计算 MongoDB 中的实例数

javascript - smoothState.js:将类添加到#main 包装器

c++ - 在队列中,插入删除后,被删除的元素也出现在Output中,为什么?

c++ - 指针数组和类型转换

javascript - 箭头函数不应返回赋值 Eslint

javascript - 如果初始值不存在,则选择第一项

c++ - 在 C++ 中为同一个类拥有 2 个头文件是否合法?

javascript - 期望 'this' 被类方法使用