jscodeshift изменить буквенное значение объекта
Используя jscodeshift, как я могу преобразовать
// Some code ...
const someObj = {
x: {
foo: 3
}
};
// Some more code ...
в
// Some code ...
const someObj = {
x: {
foo: 4,
bar: '5'
}
};
// Some more code ...
?
я пытался
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();
}
но я просто в конечном итоге
// Some code ...
const someObj = {
{"foo": 4, "bar": "5"}: {
foo: 3
}
};
// Some more code ...
что говорит о том, что replaceWith
просто меняет ключ вместо значения.
1 ответ
Вы должны искать ObjectExpression
а не для 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();
}