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

    The following would work:

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