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)
    }
  • 相关阅读:
    c语言|博客作业05
    C语言I博客作业04
    C语言II博客作业04
    C语言II博客作业03
    C语言II博客作业02
    C语言II博客作业01
    学期总结
    我的第一周C语言作业
    C语言I博客作业08
    C语言I博客作业07
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12342540.html
Copyright © 2011-2022 走看看