插入函数调用参数--babel插件妙用

69 阅读1分钟

背景:

  1. 有的时候,我们希望能够给console.log 添加一些比如代码文件参数信息等。

需求拆解

  1. 我需要寻找到ast节点类型为 console的node
  2. 需要获取到当前代码位置信息
  3. 向这个console.log里面添加参数

``

module.exports = function ({ types, template }, options) {
  return {
    visitor: {
      CallExpression(path, state) {
        if ((types.isMemberExpression(path.node.callee)
          && path.node.callee.object.name === 'console' &&
          path.node.callee.property.name === 'log')) {
          const { column, line } = path.node.loc.start
          path.node.arguments.unshift(types.stringLiteral(`${line}:${column}`))
        }


      }
    }
  }
}
// 插件形式本质上就是一个transform 插件形式

// 文件配置信息
const { transformFileSync } = require('@babel/core');
const insertParametersPlugin = require('./babel-functioninsert');
const path = require('path');

const { code } = transformFileSync(path.join(__dirname, './sourceCode.js'), {
  plugins: [insertParametersPlugin],
  parserOpts: {
    sourceType: 'unambiguous',
    plugins: ['jsx']
  }
});

console.log(code);


其实思路就是,依据types 来判断是非为表达式类型,以及判断其节点类型是否为console.log , 最后再去向其添加参数。

整体一定要结合 astexplorer.net/ 来精准的写出其节点路径。