Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将对象包装到函数中使用jscodeshift返回此对象_Jscodeshift - Fatal编程技术网

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

如何将对象包装到函数中使用jscodeshift返回此对象,jscodeshift,Jscodeshift,假设我有以下文件 export default { foo: 'bar' } 如何使用jscodeshift转换此文件,使其将对象包装成如下函数: export default () => ({ foo: 'bar' }) 我的主要问题是如何使用api.jscodeshift.arrowFunctionExpression(),尤其是如何创建函数体。因为我想我需要做的就是用一个函数替换ObjectExpression,这个函数的主体是ObjectExpression。我自己发现

假设我有以下文件

export default {
  foo: 'bar'
}
如何使用jscodeshift转换此文件,使其将对象包装成如下函数:

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

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

我自己发现的<代码>箭头函数表达式获取一个列表参数,然后获取一个
块语句
。这将生成以下函数:

const fn = j.arrowFunctionExpression(
    [{ type: "Identifier", name: "theme" }],
    j.blockStatement([j.returnStatement(stylesObject)])
  );
然后创建一个新的
exportDefaultDeclaration
,并将函数传递给它

const e = j.exportDefaultDeclaration(fn)

  return j(e).toSource(); 

另一个选项是使用
j.template.expression
,这是一个标记的模板,可以使用现有节点插入JavaScript:

:

返回j(file.source)
.查找(j.ExportDefaultDeclaration)
.find(j.ObjectExpression)
.替换为(
path=>j.template.expression`theme=>${path.node}`
)
.toSource();