Acorn / JSX - walk nodes with particular type

612 views Asked by At

I am parsing JSX (React component) to find all nodes that:

  • belong to JSXText type
  • Node has not empty parameter text

This is my first attempt to parse the component source file, with a test how to get Literal node.

const acorn = require("acorn")
const jsx = require("acorn-jsx")
const cf = require("acorn-class-fields")
const walk = require("acorn-walk")

let s = acorn.Parser.extend(cf).extend(jsx()).parse(cnt, {ecmaVersion: "latest", sourceType: "module"});
 walk.simple(s, {
Literal(node) {
                        console.log(`Literal: ${node.value}`)
                    }
})

Question

  • I found nodes types here but there aren't JSX node types - where could be found?
  • How to filter nodes with not empty text parameter?
1

There are 1 answers

1
peter.mouland On

I believe you can extend acorn-walk to include the extra types.

This plugin works for me: https://github.com/sderosiaux/acorn-jsx-walk

At the time of writing, the following is how i would implement it:



const acorn = require("acorn");
const jsx = require("acorn-jsx");
const walk = require("acorn-walk");
const { extend } = require('acorn-jsx-walk')

// setup
const parser = acorn.Parser.extend(jsx());
extend(walk.base);

// parse
const ast = parser.parse(cnt, { ecmaVersion: "latest", sourceType: 'module' });


// analys
walk.simple(ast, {
    JSXText(node) {
        console.log(node.expression)
    }
});