[英]Babel traverse to the first JSXElement
I need to add a custom attribute to components of a ReactJS app, for testing purposes.出于测试目的,我需要向 ReactJS 应用程序的组件添加自定义属性。 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.
我尝试使用 2 个不同的插件,但是,它们将该属性应用于该组件中的所有 JSXElement,我只想将其应用于第一个,否则,我最终会出现不必要的属性重复,这使得编写测试更加困难我正在努力挽救脆弱性。
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我浏览了文档,找不到如何遍历第一个 JSXElement,所以我自己尝试了几件事,但都失败了,这些是
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以下通过未定义中 firstElem 的错误
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.任何人都可以建议如何获得第一个 JSXElement。
So I found the answer by pure luck.所以我纯粹靠运气找到了答案。 I should have added in a stop() immediately after traversing the JSXElement
我应该在遍历 JSXElement 后立即添加一个 stop()
JSXElement( jsxPath )
{
jsxPath.stop();
...
The stop() function is not that will documented, in fact, none of BabelJS is that will documented for a beginner. stop() function 不会记录在案,事实上,没有一个 BabelJS 会为初学者记录。 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.
通过查看某人的插件并想知道它在那里做什么并通过反复试验发现它解决了上述问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.