Plugins - Visiting

How to visit nodes

Visitor overview

Visitor objects contain functions of the node types they intend to visit. eg.

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      FunctionDeclaration: {
        enter(node, parent) {

        },

        exit(node, parent) {

        }
      }
    }
  });
}

If you only have an enter handler then you can simplify it to:

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      FunctionDeclaration(node, parent) {

      }
    }
  });
}

Check if a node is of a certain type

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      CallExpression(node, parent) {
        return t.isIdentifier(node.callee);
      }
    }
  });
}

NOTE: Visitor aliases are also honored so you can use babel.types.isFunction.

You can alternatively pass an object that will be shallowly checked against the node. ie:

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      CallExpression(node, parent) {
        return t.isIdentifier(node.callee, { name: "require" }); // found a require call!
      }
    }
  });
}

This is far nicer than doing:

if (node.callee.type === "Identifier" && node.callee.name === "require") {

}

Checking if an Identifier is referenced

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      Identifier(node, parent) {
        this.isReferenced(); // equivalent to t.isReferenced(node, parent);
      }
    }
  });
}

Visitor aliases

Sometimes you may want to visit similar nodes, eg. FunctionDeclaration and FunctionExpression, Babel has a bunch of built-in aliases for nodes to make this easier. A full list can be found in the files under the definitions folder. Check the aliases key in the files.

For example if you wanted to visit all functions (meaing FunctionDeclaration, FunctionExpression and ArrowFunctionExpression) then you can use Function like in the following example:

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      Function(node, parent) {

      }
    }
  });
}

NOTE: You can also list multiple visitors together in a string with | like the following:

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      "ClassDeclaration|FunctionDeclaration"(node, parent) {

      }
    }
  });
}