简体   繁体   中英

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. 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. Just set it to true in the options.

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));

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.

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