簡體   English   中英

Babel 遍歷到第一個 JSXElement

[英]Babel traverse to the first JSXElement

出於測試目的,我需要向 ReactJS 應用程序的組件添加自定義屬性。 我嘗試使用 2 個不同的插件,但是,它們將該屬性應用於該組件中的所有 JSXElement,我只想將其應用於第一個,否則,我最終會出現不必要的屬性重復,這使得編寫測試更加困難我正在努力挽救脆弱性。

我瀏覽了文檔,找不到如何遍歷第一個 JSXElement,所以我自己嘗試了幾件事,但都失敗了,這些是

下面從不添加屬性

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

以下通過未定義中 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}` )
            )
        );

    }
}
}

任何人都可以建議如何獲得第一個 JSXElement。

所以我純粹靠運氣找到了答案。 我應該在遍歷 JSXElement 后立即添加一個 stop()

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

stop() function 不會記錄在案,事實上,沒有一個 BabelJS 會為初學者記錄。 通過查看某人的插件並想知道它在那里做什么並通過反復試驗發現它解決了上述問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM