• Writing your first Babel Plugin" level="1">Writing your first Babel Plugin

    Writing your first Babel Plugin" class="reference-link">Writing your first Babel Plugin

    Now that you’re familiar with all the basics of Babel, let’s tie it together with the plugin API.

    Start off with a function that gets passed the current babel object.

    1. export default function(babel) {
    2. // plugin contents
    3. }

    Since you’ll be using it so often, you’ll likely want to grab just babel.types like so:

    1. export default function({ types: t }) {
    2. // plugin contents
    3. }

    Then you return an object with a property visitor which is the primary visitor for the plugin.

    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. // visitor contents
    5. }
    6. };
    7. };

    Each function in the visitor receives 2 arguments: path and state

    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. Identifier(path, state) {},
    5. ASTNodeTypeHere(path, state) {}
    6. }
    7. };
    8. };

    Let’s write a quick plugin to show off how it works. Here’s our source code:

    1. foo === bar;

    Or in AST form:

    1. {
    2. type: "BinaryExpression",
    3. operator: "===",
    4. left: {
    5. type: "Identifier",
    6. name: "foo"
    7. },
    8. right: {
    9. type: "Identifier",
    10. name: "bar"
    11. }
    12. }

    We’ll start off by adding a BinaryExpression visitor method.

    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. BinaryExpression(path) {
    5. // ...
    6. }
    7. }
    8. };
    9. }

    Then let’s narrow it down to just BinaryExpressions that are using the === operator.

    1. visitor: {
    2. BinaryExpression(path) {
    3. if (path.node.operator !== "===") {
    4. return;
    5. }
    6. // ...
    7. }
    8. }

    Now let’s replace the left property with a new identifier:

    1. BinaryExpression(path) {
    2. if (path.node.operator !== "===") {
    3. return;
    4. }
    5. path.node.left = t.identifier("sebmck");
    6. // ...
    7. }

    Already if we run this plugin we would get:

    1. sebmck === bar;

    Now let’s just replace the right property.

    1. BinaryExpression(path) {
    2. if (path.node.operator !== "===") {
    3. return;
    4. }
    5. path.node.left = t.identifier("sebmck");
    6. path.node.right = t.identifier("dork");
    7. }

    And now for our final result:

    1. sebmck === dork;

    Awesome! Our very first Babel plugin.