简体   繁体   English

自定义 babel 插件 - 无法遍历(访问)JSXElement

[英]Custom babel plugin - cannot traverse (visit) JSXElement

I am trying to write a custom babel transform plugin.我正在尝试编写一个自定义 babel 转换插件。 When see the AST for a React component in astxplorer.net , I see JSXElement in the tree as a node.astxplorer.net中查看 React 组件的 AST 时,我将树中的 JSXElement 视为节点。

But when I try to log the path for the visitor JSXElement , nothing logs to the console.但是当我尝试记录访问者JSXElement的路径时,控制台没有任何记录。

React component反应组件

const HelloWorld = () => <span>Hello World</span>

Code to transform the component and log JSXElement while visiting访问时转换组件并记录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);
            }
          }
        };
      },
    ]
  });

If it helps, I have the transform.test.js inside an ejected create-react-app project.如果有帮助,我在弹出的create-react-app项目中有transform.test.js CRA comes with built-in preset react-app . CRA 带有内置的预设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.我使用命令jest transform.test.js运行测试,并且在 CRA jest 设置中默认应用了babel-jest转换。

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:我认为您将组件传递给 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM