[英]Custom babel plugin - cannot traverse (visit) JSXElement
我正在尝试编写一个自定义 babel 转换插件。 在astxplorer.net中查看 React 组件的 AST 时,我将树中的 JSXElement 视为节点。
但是当我尝试记录访问者JSXElement的路径时,控制台没有任何记录。
反应组件
const HelloWorld = () => <span>Hello World</span>
访问时转换组件并记录JSXElement的代码
transform.test.js
const { code, ast } = transformSync(HelloWorld, {
ast: true,
plugins: [
function myOwnPlugin() {
return {
visitor: {
JSXElement(path) {
// nothing logs to the console
console.log("Visiting: " + path);
}
}
};
},
]
});
如果有帮助,我在弹出的create-react-app
项目中有transform.test.js
。 CRA 带有内置的预设react-app
。
"babel": {
"presets": [
"react-app"
]
}
我使用命令jest transform.test.js
运行测试,并且在 CRA jest 设置中默认应用了babel-jest
转换。
我认为您将组件传递给 Babel 而不是组件的代码,您需要将实际代码转换为字符串,例如,如下所示:
const { code, ast } = transformSync(`const HelloWorld = () => <span>Hello World</span>`, {
ast: true,
plugins: [
function myOwnPlugin() {
return {
visitor: {
JSXElement(path) {
// nothing logs to the console
console.log("Visiting: " + path);
}
}
};
},
]
});```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.