[Javascript AST] 4. Continue: Report ESLint error

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript AST] 4. Continue: Report ESLint error相关的知识,希望对你有一定的参考价值。

const disallowedMethods = ["log", "info", "warn", "error", "dir"];

module.exports = {
  meta: {
    docs: {
      description: "Disallow use of console",
      category: "Best Practices",
      recommended: true
    }
  },
  create(context) {
    return {
      Identifier(node) {
        
        const isConsoleCall = looksLike(node, {
          name: "console",
          parent: {
            type: "MemberExpression",
            property: {
              name: val => disallowedMethods.includes(val)
            }
          }
        });
        // find the identifier with name ‘console‘
        if (!isConsoleCall) {
          return;
        }

        context.report({
          node,
          message: "Using {{identifier}} is not allowed",
          data: {
             identifier: node.name // console
          }
        });
      }
    };
  }
};

function looksLike(a, b) {
  return (
    a &&
    b &&
    Object.keys(b).every(bKey => {
      const bVal = b[bKey];
      const aVal = a[bKey];
      if (typeof bVal === "function") {
        return bVal(aVal);
      }
      return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal);
    })
  );
}

function isPrimitive(val) {
  return val == null || /^[sbn]/.test(typeof val);
}

 

We can use placeholder for more detail information:

"Using {{identifier}} is not allowed"

The placeholder can be found in data prop:

          data: {
             identifier: node.name // console
          }

 

以上是关于[Javascript AST] 4. Continue: Report ESLint error的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 二进制的 AST

AST抽象语法树——最基础的javascript重点知识,99%的人根本不了解

操作JavaScript的AST

AST抽象语法树——最基础的JavaScript重点知识

AST抽象语法树 Javascript版

操作JavaScript的AST