ast exployer

astexplorer.net/

@babel/traverse

Is a tool that automatically walks through an abstract syntax tree, accessing all nodes in the tree, triggering the Enter hook function when entering each node, and the exit hook function when exiting each node. Developers can modify the AST in the hook function.

@babel/types

Babeljs. IO/docs/en/bab…

@babel/ Types is an AST like LoDash library that encapsulates a number of AST related methods, greatly reducing the cost of AST conversion. There are two main functions of @babel/types. On the one hand, it can be used to verify the type of an AST node. For example, isClassMethod or assertClassMethod can be used to determine whether an AST node is a method in the class. On the other hand, you can use it to build AST nodes, for example, by calling the classMethod method to generate a new AST node of classMethod type.

path

There are many nodes in the AST, and each node may have different attributes, and there may be relationships between nodes. Path is an object that represents an association between two nodes. State: represents the state of the plug-in. You can use state to access the configuration items of the plug-in.

state

Represents the state of the plug-in. You can access the configuration items of the plug-in through state.

Below is the Remove Console plug-in, which supports the retention of required comments through annotations


"use strict";

const isArray = require('.. /lib/isArray')

module.exports = function({ types: t }) {
  return {
    name: "transform-remove-console-enhance".visitor: {
      CallExpression(path, { opts }) {
        const calleePath = path.get("callee")
        // Keep the console configured in options
        if (opts && isArray(opts.exclude)) {
          const hasTarget = opts.exclude.some(type= > {
            return calleePath.matchesPattern("console." + type)
          })

          if (hasTarget) return
        }
        
        Remove --console-disable Reserved console
        const leadingComments = path.parent.leadingComments || []
        const removeConsoleDisable = leadingComments.find(item= > item.value.trim()=== 'remove--console-disable' )
        if(removeConsoleDisable) {
          return
        }
        
        / / remove the console
        if (calleePath.matchesPattern("console".true)) {
          path.remove()
        }
      },
    },
  };
};


Copy the code