knilink / ez-jscodeshift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ez-jscodeshift

ez-jscodeshift is a wrapper around jscodeshift to simple finding and replacing AST Nodes.

Install

$ npm install -g https://github.com/knilink/ez-jscodeshift.git

Usage

ez-jscodeshift use tagged template expression to descript the filter and define node binding names.

To apply ez-jscodeshift, just simple wrap it over jscodeshift

const jz = require('ez-jscodeshift')(require('jscodeshift'));

Basic Example

jz(`it('should work', () => {
  assert.equal(foo(), 'bar');
});`)
  .ezFind`assert.equal(${'a'}, ${'b'})`
  .ezReplaceWith`expect(${'a'}).to.equal(${'b'})`
  .toSource()

Origin

it('should work', () => {
  assert.equal(foo(), 'bar');
});

Result

it('should work', () => {
  expect(foo()).to.equal('bar');
});

Custom filter

jz(`expect(r1).to.equal('foo');
expect('bar').to.equal(r2);`)
  .ezFind`expect(${['a', { type: 'Literal' }]}).to.equal(${'b'})`
  .ezReplaceWith`expect(${'b'}).to.equal(${'a'})`
  .toSource()

Origin

expect(r1).to.equal('foo');
expect('bar').to.equal(r2);

Result

expect(r1).to.equal('foo');
expect(r2).to.equal('bar');

Custom Binding

jz('myObj.myFun(...[b,c,d])')
  .ezFind`${'f'}(...${['a', { type: 'ArrayExpression', elements: (b) => ({ b }) }]})`
  .ezReplaceWith`${$ => j.callExpression($.f.value, $.b.value)}`
  .toSource();

Origin

myObj.myFun(...[b,c,d])

Result

myObj.myFun(b, c, d)

Block statement

jz(`mylist.forEach(item=>{
  console.log(item);
})`)
  .ezFind`${'list'}.forEach((${'i'})=>${'{body}'})`
  .ezReplaceWith`for(const ${'i'} of ${'list'}) ${'{body}'}`
  .toSource();

Origin

mylist.forEach(item=>{
  console.log(item);
})

Result

for(const item of list) {
  console.log(item);
};

Tagged template statement

jz("tag`foo${'bar'}baz`")
  .ezFind`tag${'`t`'}`
  .ezReplaceWith`tag2${'`t`'}`
  .toSource()

Origin

tag`foo${'bar'}baz`

Result

tag2`foo${'bar'}baz`;

Other examples

jz(`expect(foo,'my error description').to.equal('foo');`)
  .ezFind`expect(${'a'},${'comment'}).to.equal(${'b'})`
  .ezReplaceWith`expect(${'a'}).toBe(${'b'})`
  .ezReplaceWith`${($, path) => {
      const ast = path.value;
      const commentAst = $.comment.value;
      ast.expression.comments = [j.commentLine(' ' + commentAst.value)];
      return ast;
    }}`
  .toSource()

Origin

expect(foo,'my error description').to.equal('foo');

Result

// my error description
expect(foo).toBe('foo');

About

License:MIT License


Languages

Language:JavaScript 100.0%