gpt4 book ai didi

javascript - Babel unshiftcontainer 不创建元素

转载 作者:行者123 更新时间:2023-12-05 02:53:37 24 4
gpt4 key购买 nike

尝试使用 babel 转换,我编写了这段代码以在我的 path 之后插入一个 VariableDeclaration

export default function (babel) {
const { types: t } = babel;

return {
name: "ast-transform", // not required
visitor: {
VariableDeclaration (path) {
if (path.node.kind !== 'var') {
return;
}

const _id = t.Identifier('qwe');
const _init = t.numericLiteral(42);

console.log(_id, _init);

const _node = t.variableDeclaration('var', [
t.variableDeclarator(
t.identifier("uid"),
t.numericLiteral(42)
)
]);

path
.unshiftContainer(
'body',
_node
)

}
}
};
}

得到如下错误,

unknown: Cannot read property 'body' of undefined

编辑:

如果我执行以下操作而不是 unshiftContainer 它会起作用,

const _program = path.findParent(p => p.isProgram());
_program.node.body.unshift(_node);

为什么 unshiftContainer 不起作用?

链接到 ast-explorer 上的要点

最佳答案

为了使用unshiftContainer("body"),你必须有一个带有“body”的节点。例如,ProgramFunctionDeclaration(123)

但是您正试图在没有 bodyVariableDeclaration 上执行此操作,正如您在 ast-explorer 中看到的那样.

当您调用 path.get("body") 时,它返回 {..., node: undefined, ...} 然后,当您调用unshiftContainer("body"),它尝试获取 node"body",它是 undefined:容器:this.node[listKey],.

您的解决方案有效,因为您正在寻找具有主体的 Program 对象。因此,如果您想使用 unshiftContainer,这也可以工作:

const _program = path.findParent(p => p.isProgram());
_program.unshiftContainer("body", _node);

此外,您还可以这样做:

const parentWithBody = path.findParent(
(p) => p.node !== undefined && p.node.body !== undefined
);
parentWithBody.unshiftContainer("body", _node);

它不仅会检测Program,还会检测FunctionDeclaration:

来源:

var x = 10;
var y = 5;

function test() {
var z = 1;
}

输出:

var uid = 42;
var uid = 42;
var x = 10;
var y = 5;

function test() {
var uid = 42;
var z = 1;
}

关于无限循环的更新

确实,当您取消移动容器时,您正在添加新的 VariableDeclaration,因此它将进入无限循环:

  1. 查看 var x = 10 -> 添加 var uid = 42
  2. 查看 var uid = 42 -> 添加 var uid = 42
  3. 等等...

为了打破这个循环,添加这个条件,检查 node.kind 是否为 var:

if (path.node.declarations[0].init.value === 42 && path.node.declarations[0].id.name === "uid") {
return;
}

( gist )

关于javascript - Babel unshiftcontainer 不创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62117657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com