码迷,mamicode.com
首页 > 其他好文 > 详细

[AST Babel] Add function name into the console log 'path.findParent(t.isFunctionDeclaration)'

时间:2020-02-21 20:14:50      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:arguments   prim   parent   style   ||   column   div   art   amp   

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

 

[AST Babel] Add function name into the console log 'path.findParent(t.isFunctionDeclaration)'

标签:arguments   prim   parent   style   ||   column   div   art   amp   

原文地址:https://www.cnblogs.com/Answer1215/p/12342540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!