Search code examples
javascriptjscodeshift

jscodeshift - How to insert a call expression at the beginning of a blockstatement


I'm playing around with ASTs. My goal for now is to add a an identifier to every block statement in the file. But ast explorer is throwing an error that I cannot decipher.

function foo() {
   console.log('bar');
}

after mod

function foo() {
   baz
   console.log('bar');
}

AST

How does one go about adding a such thing with jscodeshift.


Solution

  • There are two things you need to be aware of

    • A block statement consists of an array of statements. You want to prepend to that array.
    • You cannot insert a bare expression (e.g. an identifier) into that array. You actually have to create an ExpressionStatement.

    The following would work:

    root
      .find(j.BlockStatement)
      .forEach((path) => {
        path.get('body').value.unshift(j.expressionStatement(j.identifier('bar')));
      });