javascriptjscodeshiftcodemod

jscodeshift throwing error: does not match type string


I am trying to transform this:

function twist() {
  this.settings = null;
  delete this.settings;
  this.whatever = null;
  this.something['hello'] = null;
  this.hello = "test";
}

into this:

function twist() {
  delete this.settings;
  delete this.settings;
  delete this.whatever;
  delete this.something['hello'];
  this.hello = "test";
}

so I wrote the following codemod for jscodeshift:

export default function transformer(file, api) {
  const j = api.jscodeshift;

  return j(file.source)
    .find(j.ExpressionStatement, {expression: j.BinaryExpression})
    .filter(p => p.value.expression.operator === "=")
    .filter(p => p.value.expression.right.type === "Literal" && p.value.expression.right.raw === "null")
    .filter(p => p.value.expression.left.type === "MemberExpression")
    .replaceWith(path => j.unaryExpression("delete", path.value.expression.left))
    //.filter(p => { console.log(p.value); return true;})
    .toSource();
}

but I get the error:

{operator: delete, argument: [object Object], prefix: true, loc: null, type: UnaryExpression, comments: null} does not match type string

Solution

  • What your code is doing is replacing the ExpressionStatement with a UnaryExpression. Replacing Statements with Expressions can be finicky.

    It also looks for a BinaryExpression, but a BinaryExpression doesn't have = as an operator.

    Your filter should actually be an AssignmentExpression instead, because what you actually want to do is to replace the AssignmentExpression inside of the ExpressionStatement with a UnaryExpression, thus replacing one Expression with another.

    export default function transformer(file, api) {
      const j = api.jscodeshift;
    
      return j(file.source)
        .find(j.AssignmentExpression, {
          operator: "=",
          right: {
            type: "Literal",
            value: null
          }
        })
        .replaceWith(({ node: { left } }) => j.unaryExpression("delete", left))
        .toSource();
    }
    

    Here's an ASTExplorer example: https://astexplorer.net/#/gist/afb441a9709f82cd6fc3ba2860c98823/6f21cdb12a5a43aa1ca460aaa40d9ef63e1ef4bc