前端埋点babel插件babel-plugin-inflow

2020-04-03  本文已影响0人  dmaria58
前言

一般代码中的埋点方式,都太过侵入试,且无法应对不同模式、环境做出不同的调整。
此处我们先举例一种比较常见的埋点方式:

function bfun(num){
    inFlowfun(num) //埋点方法
    //以下为具体实现代码
    console.log('bfun',num)
}

或者以react为例

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      password: '',
    };
  }
  testfun(){
    inFlowfun() //埋点方法
    console.log(1)
  } 
}  

除了代码侵入性强之外,还比较难对不同环境以及开发模式做出相应的埋点调整。例如,我们一般的开发模式不需要时事埋点并且监听用户行为,但是生产发布的模式又需要实现具体埋点业务。那有什么更优雅的方式实现埋点呢?
针对以上场景,我下面介绍下代码注入babel插件babel-plugin-inflow的使用方式

安装

npm install --save-dev babel-plugin-inflow

.babelrc配置

{
  "presets": ["es2015", "stage-0"],
  "plugins": ["babel-plugin-inflow"],  //新增babel-plugin-inflow
}

.inflow文件配置(新建此文件,并且和.babelrc同级)

{
    "key":"inflow", 
    "debug":[{      
       "key":"process.env.NODE_ENV",
       "value":"develop",
       "debugKey":"inFlowfun"
    }]
}

inflow 表示识别埋点方法标志位,inflow为默认值
debug中对应的内容可以理解为,
if(process.env.NODE_ENV=="develop"){
将关键字inFlowfun替换为console.log,如果debugkey为空或者不存在,则满足if的条件时不埋点}

具体实例:

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      password: '',
    };
  }
  /*@inflow inFlowfun(1)*/
  testfun(){
    console.log(1)
  } 
}  

如果按照以上.inflow配置,经过babel-plugin-inflow编译后将实现如下逻辑

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      password: '',
    };
  }
  testfun(){
    if(process.env.NODE_ENV=="develop"){
        console.log(1)
    } 
    else{
        inFlowfun(1)
    }
    console.log(1)
  } 
}  

如果.inflow配置如下

{
    "key":"inflow", 
    "debug":[{      
       "key":"process.env.NODE_ENV",
       "value":"develop"
    }]
}

如果按照以上.inflow配置,经过babel-plugin-inflow编译后将实现如下逻辑

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      password: '',
    };
  }
  testfun(){
    if(process.env.NODE_ENV!="develop"){
        inFlowfun(1)
    }
    console.log(1)
  } 
}  

如果.inflow文件不新建,或者内容为空,则实例将被编译为

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      password: '',
    };
  }
  testfun(){
    inFlowfun(1) //埋点方法
    console.log(1)
  } 
}  

简单来讲,我们通过 babel-plugin-inflow插件,可以实现在方法前使用注释的方式,优雅的埋点。而且可以通过配置,实现例如开发模式打印出埋点内容,生产模式实现具体埋点。
插件具体github地址以及详细使用说明:https://github.com/dmaria58/babel-plugin-inflow

上一篇下一篇

猜你喜欢

热点阅读