【问题标题】:Create a codemod to add a new element to array创建一个 codemod 以将新元素添加到数组
【发布时间】:2019-10-15 19:26:38
【问题描述】:

我一直在努力使用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上玩它

【问题讨论】:

    标签: javascript abstract-syntax-tree jscodeshift


    【解决方案1】:

    .closest 返回与类型匹配的最近的 ancestor 节点。 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();
    };
    

    【讨论】:

    • 非常感谢您的回答)
    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 2023-04-04
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多