2

我一直在努力将新对象添加到具有jscodeshift. 我的问题是我无法弄清楚在获得VariableDeclarator. 我需要在数组中获取最后一个元素,然后才能插入一个新节点。这是代码:

export default function transformer(file, api) {

    const j = api.jscodeshift;
    const root = j(file.source);
    const changeList = root.find(j.VariableDeclarator, {
        id: {name: 'list'},
    }).closest(j.ArrayExpression, {
        elements: [""]
    }).replaceWith(p => {
        console.log(p);
    }).toSource();

};

我在AST explorer上玩它

4

1 回答 1

3

.closest返回与类型匹配的最近的祖先节点。虽然这ArrayExpression是一个后代,所以你必须.find再次使用。这有效:

export default function transformer(file, api) {

  // import jscodeshift
    const j = api.jscodeshift;
    // get source code 

    const root = j(file.source);
    // find a node

    return root.find(j.VariableDeclarator, {id: {name: 'list'}})
    .find(j.ArrayExpression)
    .forEach(p => p.get('elements').push(j.template.expression`x`))
    .toSource();
};
于 2019-10-17T09:12:13.833 回答