简体   繁体   中英

Babel traverse to the first JSXElement

I need to add a custom attribute to components of a ReactJS app, for testing purposes. I have tried to use 2 different plugins, however, they apply the attribute to all JSXElements within that component and I want to apply it to just the first, otherwise, I end up with unnecessary duplication of the attribute which makes writing the tests even harder and I'm trying to save fragility.

I have gone through the docs and cannot find how to traverse to the first JSXElement, so have tried a couple of things myself and failed, these are

The below never adds the attribute

visitor: {
    JSXElement( path, state ) {
        if ( path.key === 0 )
        {
            path.node.openingElement.attributes.push(
                t.jSXAttribute(
                    t.jSXIdentifier( 'data-e2e' ),
                    t.stringLiteral( `${someValue}` )
                )
            );
        }
    }
}

The below throughs error that firstElem in undefined

visitor: {
    Program( path, state ) {
        let arr = [];

        path.traverse( {
            enter( jsxPath )
            {
                if ( jsxPath.node.type === 'JSXElement' )
                {
                    arr.push( jsxPath );
                }
            }
        } );
        let firstElem = arr[ 0 ];   <<< undefined
        firstElem.node.openingElement.attributes.push(
            t.jSXAttribute(
                t.jSXIdentifier( 'data-e2e' ),
                t.stringLiteral( `${someValue}` )
            )
        );

    }
}
}

Can anyone suggest how to get just the first JSXElement.

So I found the answer by pure luck. I should have added in a stop() immediately after traversing the JSXElement

JSXElement( jsxPath )
      {
        jsxPath.stop(); 
    ...

The stop() function is not that will documented, in fact, none of BabelJS is that will documented for a beginner. Found this by looking at a someone's plugin and wondering what it was doing there and by trial and error, found it resolved the above propblem.

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