Dis*_*tum 6 javascript jscodeshift
使用jscodeshift,我该如何转换
// Some code ...
const someObj = {
x: {
foo: 3
}
};
// Some more code ...
Run Code Online (Sandbox Code Playgroud)
到
// Some code ...
const someObj = {
x: {
foo: 4,
bar: '5'
}
};
// Some more code ...
Run Code Online (Sandbox Code Playgroud)
?
我努力了
module.exports = function(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
return root
.find(j.Identifier)
.filter(path => (
path.node.name === 'someObj'
))
.replaceWith(JSON.stringify({foo: 4, bar: '5'}))
.toSource();
}
Run Code Online (Sandbox Code Playgroud)
但我最终得到的是
// Some code ...
const someObj = {
{"foo": 4, "bar": "5"}: {
foo: 3
}
};
// Some more code ...
Run Code Online (Sandbox Code Playgroud)
这表明replaceWith只更改键而不是值。
您必须搜索 theObjectExpression而不是Identifier:
module.exports = function(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
j(root.find(j.ObjectExpression).at(0).get())
.replaceWith(JSON.stringify({
foo: 4,
bar: '5'
}));
return root.toSource();
}
Run Code Online (Sandbox Code Playgroud)