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