code to ast
const { parse } = babel;
const code = `
for (let k in ${data}) {
let ${path.__cxt} = _setCxt(k, ${data});
}
`;
const ast = parse(code);
ast to code
const { default: generate } = require("@babel/generator");
const { code } = generate(path.node);
在顶层添加静态函数
function _setCxt(k, data) {
}
// https://babeljs.io/docs/en/babel-traverse
traverse(state.file.ast, {
Program(path) {
path.unshiftContainer("body", parse(`${_setCxt}`).program.body[0]);
}
});
// or
export default function (babel) {
return {
visitor: {
Program: {
enter(path) {
path.unshiftContainer("body", parse(`${_setCxt}`).program.body[0]);
}
}
}
};
}
获取父节点
path.parent; // node
path.parentPath // path
// 返回true则返回查找到的parent,可以返回false来遍历父节点。
path.findParent(pPath => {
return true;
})
path类型判断
path.type === "Identifier";
path.isIdentifier();
用另一个替换当前节点
const { types: t } = babel;
// replaceWith(replacement: Node | NodePath): void;
path.replaceWith(t.Identifier("a"));
删除path
path.remove()