[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)
}

 

posted @ 2020-02-21 18:41  Zhentiw  阅读(266)  评论(0编辑  收藏  举报