简体   繁体   English

在 babel 解析器中找不到 JSXElement

[英]Can not find JSXElement in babel parser

I'm writing a plugin to modify the code of JSX files, but the babel parser just can not find any JSXElement in the code.我正在编写一个插件来修改 JSX 文件的代码,但是 babel 解析器在代码中找不到任何 JSXElement。 Is there something wrong with my code?我的代码有问题吗?

import babel from "@babel/core";
import * as t from "@babel/types";

const code = "export const TagItem = (props)=> { return <div><h1>{props.tag.text}</h1></div>}";

const output = babel.transformSync(code, {
  sourceType: "module",
  plugins: [
  "@babel/plugin-syntax-jsx",
    function myCustomPlugin() {
      return {
        visitor: {
          Identifier(path) {
            if (t.isJSXElement(path.node)) {
              console.log("JSXElement found");
            }
          },
        },
      };
    },
  ],
});

console.log(JSON.stringify(output));

I've found the answer on my own.我自己找到了答案。 The ast output is turned off by default for performance issues. ast output 因性能问题默认关闭。 Just set it to true in the options.只需在选项中将其设置为 true。

import babel from "@babel/core";
import * as t from "@babel/types";

const code = "export const TagItem = (props)=> { return <div><h1>{props.tag.text}</h1></div>}";

const output = babel.transformSync(code, {
  sourceType: "module",
  ast: true,
  plugins: [
  "@babel/plugin-syntax-jsx",
    function myCustomPlugin() {
      return {
        visitor: {
          Identifier(path) {
            if (t.isJSXElement(path.node)) {
              console.log("JSXElement found");
            }
          },
        },
      };
    },
  ],
});

console.log(JSON.stringify(output));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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