JSCodeShift:如何将对象属性包装到另一个属性中



我是jscodeshift的新手,我正在使用它来转换现有代码,我几乎已经实现了所有目标,但我被困在需要转换现有对象的部分(一个文件中可能有多个对象)。我在网上找不到一个好的示例代码,我可以获得属性,但我不知道如何转换它们,我尝试了几种方法,但都没有成功。

输入:

const apiConfig = {
url,
location,
method: 'GET',
params: {
test: 'test'
},
spinnerConfig: {
...
}
}

预期输出:

const apiConfig = {
apiRequestOptions: { 
url,
location,
method: 'GET',
params: {
test: 'test'
},
spinnerConfig: {
...
},
},
}

Jscodeshift:

export const parser = 'tsx'
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
return root
.find(j.ObjectExpression)
.filter(x => x.parentPath.parentPath.value.id.name == 'apiConfig')
.forEach((path) => {
// For each object literal 
path.value.properties.forEach((property) => {
// go through each property
if (property.type !== "ObjectProperty") return;
// transform the obj here
})
}).toSource();
}

编辑:我能够转换它。

更新代码:

export const parser = 'tsx'
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
return root
.find(j.ObjectExpression)
.filter(x => x.parentPath.parentPath.value.id.name == 'apiConfig')
.forEach((path) => {
const newObj = j.property(
'init',
j.identifier('apiRequestOptions'),
j.objectExpression([
...path.value.properties // spread the properties
])
);
path.value.properties = [] // mutate original 
path.value.properties.push(newObj) // add a new one
})
}).toSource();
}

这就是使用我正在开发的Putout:工具解决问题的方法

export const match = () => ({
'const apiConfig = __object': ({__object}, path) => {
const [property] = __object.properties;
return property.key.name !== 'apiRequestOptions';
}
});
export const replace = () => ({
'const apiConfig = __object': ({__object}, path) => {
const {properties} = __object;

__object.properties = [
ObjectProperty(Identifier('apiRequestOptions'), ObjectExpression(properties))
]

return path;
}
});

你可以在Putout Editor中查看它。

  • match-仅在缺少apiRequestOption时保留修复
  • __object根据PutoutScript检查ObjectExpressionObjectPattern

最新更新