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



假设我有以下文件

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(); 

最新更新