-
Notifications
You must be signed in to change notification settings - Fork 0
/
babel-plugin-print-log.js
40 lines (35 loc) · 1.35 KB
/
babel-plugin-print-log.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const generator = require('@babel/generator').default
// babel 插件的写法
// step1 生成ast
// step2 插入log
// step3 生成目标代码
const targetCalleeName = ['log', 'info', 'error', 'debug'].map(item => `console.${item}`);
module.exports = (api, options, dirname) => {
// console.log(Object.keys(api))
// console.log(options)
// console.log(dirname)
// console.log('-----')
const { types, template } = api
return {
visitor: {
CallExpression(path, state) {
if (path.node.isNew) {
return;
}
const calleeName = generator(path.node.callee).code;
if (targetCalleeName.includes(calleeName)) {
const { line, column } = path.node.loc.start;
const fileName = (state && state.filename) || 'unkown filename'
const newNode = template.expression(`console.log("${fileName}: (${line}, ${column})")`)();
newNode.isNew = true;
if (path.findParent(path => path.isJSXElement())) {
path.replaceWith(types.arrayExpression([newNode, path.node]))
path.skip();
} else {
path.insertBefore(newNode);
}
}
}
}
}
}