Is it possible to place a whole function in babel's block statement

Viewed 9

I am trying to write a babel plugin using AST that will change the arrow function of React usememos hook to my own custom function.

This is a basic use memo function I am using to explore the syntax tree.


const  data = useMemo(() => {
    return "Hello"
    }, [])

I would love to change the arrow function in the above function to the one below on compile


async function handler() {
  const response = await window
    .fetch(`https://jsonplaceholder.typicode.com/todos/1`, {
      method: `GET`,
      headers: {
        "content-type": "application/json"
      }
    })
    .then((res) => res.json());

  return response;
}

My babel code


module.exports = function (babel) {
  const { types: t } = babel;

  return {
    name: "change-gatsby-function", // not required
    visitor: {
      ArrowFunctionExpression(path) {
        if (path.parent.callee === undefined) {
          return;
        }
        if (path.parent.callee.name === "useMemo") {
          path.replaceWith(
            t.ArrowFunctionExpression([], t.blockStatement(), true)
          );
        }
      }
    }
  };
};

If I try adding the block directly into the block statement I get an error. Whats the best way to convert the arrow function to the new function on compile?

0 Answers
Related