zoukankan      html  css  js  c++  java
  • [AST Babel] Add function name into the console log 'path.findParent(t.isFunctionDeclaration)'

    Continue with the previous post: https://www.cnblogs.com/Answer1215/p/12337243.html

    What we want to do in this post, is adding parent function name into the console log as well:

    Previous output is :

    function add(a, b) {
        console.log("2:4", a, b)
          return a + b
    }
    
    function subtract(a, b) {
        console.log("7:4", a, b)
          return a - b
    }
    
    add(1, 2)
    subtract(2, 1)
    console.log("13:0", 'sup dawg')

    Now we want:

    function add(a, b) {
        console.log("add 2:4", a, b)
          return a + b
    }
    
    function subtract(a, b) {
        console.log("subtract 7:4", a, b)
          return a - b
    }
    
    add(1, 2)
    subtract(2, 1)
    console.log("13:0", 'sup dawg')

    The key is using 

    path.findParent()

    +

    t.isFunctionDeclaration

    To find its parent function.

    Code:

    export default function (babel) {
      const { types: t } = babel;
     
      return {
        name: "ast-transform", // not required
        visitor: {
          CallExpression(path) {
              if (!looksLike(path.node, {
                callee: {
                  type: 'MemberExpression',
                  object: {
                      name: 'console'
                  },
                  property: {
                      name: 'log'
                  }
                }
            })) {
              return
            }
            
            const parentFn = path.findParent(t.isFunctionDeclaration);
            const fnName =  parentFn? 
                  `${parentFn.node.id.name} `: 
                  '';
            // insert string into console.log('instread here', a,b)
            const {line, column} = path.node.loc.start;
            const prefix = fnName + `${line}:${column}`;
            path.node.arguments.unshift(t.stringLiteral(prefix))
          }
        }
      };
    }
    
    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)
    }
  • 相关阅读:
    iOS自己主动化測试的那些干货
    RecylerView 的使用方法
    java 获取局域网中的全部主机名和IP地址
    C++项目參考解答:求Fibonacci数列
    tableView的用法具体解释
    【jQuery小实例】---3 凤凰网首页图片动态效果
    【jQuery小实例】---2自定义动画
    【jQuery小实例】js 插件 查看图片
    【url重写】
    【文件上传】
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12342540.html
Copyright © 2011-2022 走看看