I am trying to write a custom babel transform plugin. When see the AST for a React component in astxplorer.net , I see JSXElement in the tree as a node.
But when I try to log the path for the visitor JSXElement , nothing logs to the console.
React component
const HelloWorld = () => <span>Hello World</span>
Code to transform the component and log JSXElement while visiting
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);
}
}
};
},
]
});
If it helps, I have the transform.test.js
inside an ejected create-react-app
project. CRA comes with built-in preset react-app
.
"babel": {
"presets": [
"react-app"
]
}
I run the test with the command jest transform.test.js
and I have babel-jest
transform applied by default in CRA jest setup.
I think you're passing the component to Babel instead of the code for the component, you need to transform the actual code as a string, for example, something like this:
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);
}
}
};
},
]
});```
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.