发布网友 发布时间:2024-10-23 22:41
共1个回答
热心网友 时间:2024-11-01 11:53
作为一名前端开发工程师,我们会经常使用console来调试代码,但随着代码量的不断增多,日志变的杂乱无章,尤其多人配合后,想找出关键信息变得十分困难。今天我们借助babel来规范日志。
思路我们可以在每一处consle.xxx加一些关键信息前缀(如下),怎么实现呢,当然是今天的主角babel-loader。
实现通过babel的遍历,找出代码中的console
在线AST地址:astexplorer.net/
module.exports=()=>{return{visitor:{CallExpression(path,state){if(path.node.callee.object&&path.node.callee.object.name==='console'){console.log('我找到了console对象');}}}}}获取表达式路径上的信息
constbasename=require("path").basename;module.exports=()=>{return{visitor:{CallExpression(path,state){if(path.node.callee.object&&path.node.callee.object.name==="console"){//文件的名称constfilename=state.file.opts.filename;constname=basename(filename);//打印的位置信息constlocation=`${path.node.loc.start.line}:${path.node.loc.start.column}`;console.log(`name:${name}\nlocation:${location}`);}},},};};插入节点
constbasename=require("path").basename;module.exports=()=>{return{visitor:{CallExpression(path,state){if(path.node.callee.object&&path.node.callee.object.name==="console"){//文件的名称constfilename=state.file.opts.filename;constname=basename(filename);//打印的位置信息constlocation=`${path.node.loc.start.line}:${path.node.loc.start.column}`;console.log(`name:${name}\nlocation:${location}`);path.node.arguments.unshift({type:'StringLiteral',value:`[${name}${location}]`})}},},};};借助webpack引入babel-loader和我们的插件,如下配置
//webpack.config.jsconstconsolePrefix=require('../lib/index')......module:{rules:[{test:/\.js$/,use:[{loader:'babel-loader',options:{plugins:[consolePrefix]}}]}]}优化上述例子已经实现了大多数需求,为了让插件有更多的功能以及更好的兼容,完整代码在[github]
作者:莱米