假设我有以下文件
export default {
foo: 'bar'
}
如何使用 jscodeshift 转换此文件,以便它将对象包装成这样的函数:
export default () => ({
foo: 'bar'
})
我的主要问题是如何使用api.jscodeshift.arrowFunctionExpression()
,尤其是如何创建函数体。因为我认为我需要做的就是用一个以ObjectExpression
为主体的函数替换ObjectExpression
。
另一种选择是使用j.template.expression
这是一个标记模板,可让您将 JavaScript 与现有节点进行插值:
完整示例:
return j(file.source)
.find(j.ExportDefaultDeclaration)
.find(j.ObjectExpression)
.replaceWith(
path => j.template.expression`theme => ${path.node}`
)
.toSource();
我自己发现的。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();