1

假设我有以下文件

export default {
  foo: 'bar'
}

如何使用 jscodeshift 转换此文件,以便将对象包装成如下函数:

export default () => ({
  foo: 'bar'
})

我的主要问题是如何使用api.jscodeshift.arrowFunctionExpression(),尤其是如何创建函数体。因为我认为我需要做的就是ObjectExpression用具有ObjectExpression作为其主体的函数替换。

4

2 回答 2

2

另一种选择是使用j.template.expression它是一个标记模板,它允许您使用现有节点插入 JavaScript:

完整的例子

  return j(file.source)
    .find(j.ExportDefaultDeclaration)
    .find(j.ObjectExpression)
    .replaceWith(
      path => j.template.expression`theme => ${path.node}`
    )
    .toSource();
于 2019-12-19T21:28:02.843 回答
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(); 
于 2019-12-18T10:11:42.397 回答