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

    Start off with a that gets passed the current object.

    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. };
    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. Identifier(path, state) {},
    5. ASTNodeTypeHere(path, state) {}
    6. }
    7. };

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

    Or in AST form:

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

    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. }
    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:

    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");
    1. sebmck === dork;

    Awesome! Our very first Babel plugin.