Need help performing code transformations #11736
-
Hello! I’m new to working with babel and I’m trying to use the visitor pattern to perform some AST traversal and transformations. The JS code I want to transform is:
I’m currently looking through all call expressions to identify the .attr() call with the first arg being “height” which I’m able to find with ease. I’m trying to insert the following code after the call expression but before the “;”
Basically I want to transform the code from
To
However, the code is added after the whole expression and that’s not what I want. I can’t figure out what I’m doing wrong and need help and suggestions on how to handle this. I would also appreciate if someone could point me to a really good tutorial on how to perform complex JS code transformations with Babel (I’ve already seen most of the reversing identifiers examples) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
So you want to transform You need to wrap the existing CallExpression into a MemberExpression and a new CallExpression with export default function (babel) {
const { types: t } = babel;
return {
name: "ast-transform", // not required
visitor: {
CallExpression: {
exit(path) {
if (path.node.callee.type === "MemberExpression") {
if (path.node.callee.property.name == "attr") {
if (path.node.arguments[0].value == "height") {
console.log(path.node.arguments[1].body);
path.replaceWith(
t.callExpression(t.memberExpression(path.node, t.identifier("on")), [
t.stringLiteral("mouseover"),
t.memberExpression(t.identifier("tip"), t.identifier("show"))
])
);
path.skip(); // to somehow prevent infinite recursion
}
}
}
}
}
}
};
} |
Beta Was this translation helpful? Give feedback.
So you want to transform
CallExpression(...)
intoCallExpression(MemberExpression(OldCallExpression, 'on'), ...args)
You need to wrap the existing CallExpression into a MemberExpression and a new CallExpression with
replaceWith
: