rob*_*111 4 javascript abstract-syntax-tree jscodeshift
我一直在努力将新对象添加到对象数组中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();
};
Run Code Online (Sandbox Code Playgroud)
我正在AST 浏览器上玩它
.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();
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |