zoukankan      html  css  js  c++  java
  • [Javascript AST] 3. Continue: Write ESLint rule

    The rule we want to write is show warning if user using console method:

    // valid
    foo.console()
    console()
    info()
    console.baz()
    
    // invalid
    console.log()
    console.info()
    console.warn()

    Rule:

    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 console is not allowed"
            });
          }
        };
      }
    };
    
    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);
    }

    'looksLike' & isPrimitive is pretty handy, you can save as until lib.

  • 相关阅读:
    01 网络基础
    01 ansible的基本介绍
    10 面向对象的编程
    03 docker容器镜像基础
    09 异常处理
    08 输入输出
    07 数据结构
    02 docker的基本用法
    01 docker容器技术基础入门
    06 字符串
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7594742.html
Copyright © 2011-2022 走看看