zoukankan      html  css  js  c++  java
  • [AST Babel Plugin] Transform code, add line:column number for console log

    For example we have current code:

    function add(a, b) {
        console.log(a, b)
          return a + b
    }
    
    function subtract(a, b) {
        console.log(a, b)
          return a - b
    }
    
    add(1, 2)
    subtract(2, 1)
    console.log('sup dawg')

    We want to transform the code to:

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

    Added line and colum number in front of console log arguements

    Using the utilites functions:

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

    Babel plugin 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
            }
            console.log(path.node.loc)
            // insert string into console.log('instread here', a,b)
            const {line, column} = path.node.loc.start;
            path.node.arguments.unshift(t.stringLiteral(`${line}:${column}`))
          }
        }
      };
    }
  • 相关阅读:
    设计模式-外观模式
    发生死锁怎么办
    设计模式-工厂模式
    设计模式-模板方法
    设计模式-命令模式(Command)
    设计模式-单例模式
    设计模式-装饰器模式
    CQRS之旅——旅程8(后记:经验教训)
    CQRS之旅——旅程7(增加弹性和优化性能)
    CQRS之旅——旅程6(我们系统的版本管理)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12337243.html
Copyright © 2011-2022 走看看