jscodeshift-collections

Extra collections api for jsdcodeshift


Keywords
jscodeshift, collections, ast, recast, abstract syntax tree, codemod, codemods, collection, hacktoberfest, hacktoberfest-accepted
License
MIT
Install
npm install jscodeshift-collections@1.1.0

Documentation

jscodeshift-collections

Build and Deploy npm version Coverage Status semantic-release Conventional Commits

Some more Collections for jscodeshift for easy and terse api for writing Codemods

Install

npm install jscodeshift-collections

List of collections

Usage

const jscsCollections = require('jscodeshift-collections');

module.exports = function(fileInfo, api) {
  const j =  api.jscodeshift;

  jscsCollections.registerCollections(j);

  return j(fileInfo.source)
    .findFunctionDeclarations('foo')
    .renameTo('bar')
    .toSource();
}

Example

Say for example, if you want to rename a function declaration foo to bar

Transform with new Collection API

j.findFunctionDeclarations('foo')
 .renameTo('bar')

Before

function foo() {
}

After

function bar() {
}

List of Collections:

FunctionDeclaration

// Find all function declarations
j.findFunctionDeclarations()

// Find all function declarations with name=foo and rename them to bar
j.findFunctionDeclarations('foo')
    .renameTo('xyz');

// Find and remove params
  j.findFunctionDeclarations('bar')
    .removeParam('a');

// Find and add params
  j.findFunctionDeclarations('bar')
    .addParam('d');

CallExpression

// Find all call expressions
  j.findCallExpressions();

// Find all member expressions
  j.findCallExpressions('foo.bar');


// Find all nested member expressions
  j.findCallExpressions('foo.bar.baz');

// Find and rename call expressions
  j.findCallExpressions('foo')
  .renameTo('xyz');

// Find and rename member expressions
  j.findCallExpressions('foo')
  .renameTo('foo.bar');

//  Find and remove params
  j.findCallExpressions('bar')
  .removeParam('a');

// Find and add params
  j.findCallExpressions('bar')
  .addParam('d');

ImportDeclaration

// Find all import declarations
  j.findImportDeclarations();

// Find and rename
  j.findImportDeclarations('a')
  .renameTo('xyz');

// Find and remove specifiers
  j.findImportDeclarations('a')
  .removeSpecifier('a');

// Find and add specifiers
  j.findImportDeclarations('a')
  .addSpecifier('c');