如何使用ESLint自定义规则分析JS文字/标识符

问题描述

我将通过一个示例来说明这种情况。

假设我有以下JS代码

There are no metrics in this namespace for the region "Europe (London)"

我想将调用限制在控制器的那个动作上。因此,我为此编写了以下Custom ES Lint规则:

$.ajax({
    url: '/Department/GetAllUsers',type: "POST",data: data,success: function (result) {
        //Some Code
    },error: function () {
        //Some Code
    }
});

所以在这里,我限制使用'部门/ GetAllUsers'效果很好。当我分割字符串或将字符串分配给变量时,就会出现问题。例如

module.exports = {
    Meta: {
        type: "problem",docs: {
            description: "Prohibited Method",category: "Method",recommended: true,url: ""
        },messages: {
            messageDefault: "This method is Prohibited to use"
        },fixable: "code",schema: [] // no options
    },create: function (context) {
        return {
            Literal(node) {
                var literalValue = node.value.toString();
                var cont = literalValue.split("/").filter(x => x.length > 1);
                {
                    if (cont[0] === 'Department' && cont[1] === 'GetAllUsers') {

                        context.report({
                            node: node,messageId: "messageDefault",});
                    }
                }
            }
        };
    }
};

这里限制不起作用,有没有办法我可以解析URL上的变量值?使用ESLint甚至有可能吗?

简而言之,我想要像context.SemanticModel.GetSymbolInfo(node)这样的东西,它在Roslyn中用于C#代码分析。

谢谢

解决方法

您可以使用ESLint的范围管理器 https://eslint.org/docs/developer-guide/scope-manager-interface

在ESLint自己的代码库中有很多使用范围管理器的示例: https://github.com/eslint/eslint/search?q=getScope

使用此API,您可以遵循变量引用并检查其分配。

请注意,这有一些限制。例如,您将无法跨模块边界或函数边界跟踪值。