我正在开发一个SWC Rust WASM插件来转换JavaScript。
整体SWC及其API设计良好。然而,目前我很难转换
TaggedTemplateExpression
到
CallExpression
就像在这个例子中一样:
console.log`Hello, ${name}!`;
到
console.log("Hello, ", name, "!");
在巴贝尔,这种转变将相对简单。以下是它的外观示例:
const babel = require("@babel/core");
function transform({ types: t }) {
return {
visitor: {
TaggedTemplateExpression(path) {
const { tag, quasi } = path.node;
if (
t.isMemberExpression(tag) &&
t.isIdentifier(tag.object, { name: "console" }) &&
t.isIdentifier(tag.property, { name: "log" })
) {
let args = [];
quasi.quasis.forEach((element, index) => {
args.push(t.stringLiteral(element.value.raw));
if (index < quasi.expressions.length) {
args.push(quasi.expressions[index]);
}
});
path.replaceWith(
t.callExpression(
t.memberExpression(
t.identifier("console"),
t.identifier("log")
),
args
)
);
}
},
},
};
}
我发现的“更改AST类型”部分
SWC CheatSheet
但我仍然不知道如何正确转换:
use swc_core::ecma::{
ast::*,
visit::{VisitMut, VisitMutWith},
};
struct TemplateToCallTransform;
impl VisitMut for TemplateToCallTransform {
fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) {=
// How do I replace the current node with the new CallExpr?
}
}