2017-04-11 27 views
2

使用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只是改变的关键,而不是价值。

回答

0

你要搜索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(); 
} 

Demo