如何将对象包装到函数中,使用jscodeshift返回此对象

时间:2019-12-15 22:15:41

标签: jscodeshift

假设我有以下文件

<div class="container" style="margin-top:30px">
        <div class="row" >
          <div class="col-sm-12"*ngFor="let witness of webService.edit_witness_list | async" >
            <h2>Would you like to edit/delete your post</h2>
            <form [formGroup]="form" (ngSubmit)="onSubmit()" >
              <div class="form-group">
                 <label for="Email">Email</label> <input type="text" id="Email"
                  name="Email" class="form-control" formControlName="Email" placeholder="Email"
                  [ngClass]="{'error': invalid('Email')}"> </div>
              <div class="form-group"> <label for="Description">Please provide details as a witness of this accident</label>
                <textarea  id="Description" rows="3" name="Description" class="form-control" formControlName="Description" placeholder="Hello"
                  [ngClass]="{'error': invalid('Description')}"></textarea> </div>
              <div class="form-group"> <label for="Date">Date of witness</label> <input [matDatepicker]="myDatepicker" id="Date" name="Date" value="03/03/1998"
                  class="form-control" formControlName="Date" readonly [ngClass]="{'error': invalid('Date')}">  <mat-datepicker-toggle [for]="myDatepicker"></mat-datepicker-toggle>
                  <mat-datepicker #myDatepicker></mat-datepicker></div>
              <div class="form-group"> <label for="Time">Time of witness</label> <input type="time" id="Time" name="Time"
                  class="form-control" formControlName="Time" value= "" mdbInput [ngClass]="{'error': invalid('Time')}"> </div>
              <span *ngIf="isIncomplete()"> You must complete all fields</span>
              <button *ngIf="!Incomplete()" type="submit" class="btn btn-primary">Submit</button>
            </form>
          </div>
        </div>
      </div>

如何使用jscodeshift转换此文件,以便将对象包装为如下功能:

export default {
  foo: 'bar'
}

我的主要问题是如何使用export default () => ({ foo: 'bar' }) ,尤其是如何创建函数体。因为我认为我要做的就是用以api.jscodeshift.arrowFunctionExpression()为主体的函数替换ObjectExpression

2 个答案:

答案 0 :(得分:1)

另一种选择是使用j.template.expression,这是一个带标签的模板,可让您将JavaScript插入现有节点:

Complete example

  return j(file.source)
    .find(j.ExportDefaultDeclaration)
    .find(j.ObjectExpression)
    .replaceWith(
      path => j.template.expression`theme => ${path.node}`
    )
    .toSource();

答案 1 :(得分:0)

由我自己发现。 arrowFunctionExpression接受列表参数,然后接受blockStatement。这将生成函数:

const fn = j.arrowFunctionExpression(
    [{ type: "Identifier", name: "theme" }],
    j.blockStatement([j.returnStatement(stylesObject)])
  );

然后创建一个新的exportDefaultDeclaration并将函数传递给它。

const e = j.exportDefaultDeclaration(fn)

  return j(e).toSource();