How to add a param to a CallExpression with jscodeshift

578 views Asked by At

I have a CallExpression like

myFunc(param1, param2, insert_here_param_3);

how to insert a param like that at the last place in of a function?

Since jscodeshift is undocumented I cannot really give an example other than the starting one.

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

  return j(file.source)
    .find(j.Identifier)
    .forEach(path => {
      if(path.node.name === "myFunc") {
        // j(path). ???
      }
    })
    .toSource();
}
1

There are 1 answers

0
Rajasegar On

There are different ways you can do this. First you can replace the entire CallExpression with a new one like this:

// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = 'babel'

// Press ctrl+space for code completion
export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);
  const body = root.get().value.program.body;

  root.find(j.CallExpression, {
    callee: {
      name: "myFunc"
    }
  }).filter(path => {
    return path.value.arguments[0].name === "param1" && path.value.arguments[1].name === "param2";
  }).replaceWith(path => {
    return j.callExpression(
      j.identifier("myFunc"),
      [j.identifier("param1"), j.identifier("param2"), j.identifier("param_3")]
    );
  });

  return root.toSource();
}

Or you can simply add a new parameter like this:

// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = 'babel'

// Press ctrl+space for code completion
export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);
  const body = root.get().value.program.body;

  root.find(j.CallExpression, {
    callee: {
      name: "myFunc"
    }
  }).filter(path => {
    return path.value.arguments[0].name === "param1" && path.value.arguments[1].name === "param2";
  }).forEach(path => {
    path.value.arguments.push(j.identifier('param_3'))
  });

  return root.toSource();
}