11import {
22 type Estree ,
3+ extractJsx ,
34 extractJsxFromEstree ,
45 type Hast ,
56 isMdxJsxElementHast ,
@@ -14,6 +15,12 @@ import { toEstree } from "hast-util-to-estree";
1415 */
1516export const rehypeExtractAsides : Unified . Plugin < [ ] , Hast . Root > = ( ) => {
1617 return ( ast ) => {
18+ // Extract module-level ESM bindings from the full AST before extracting the Aside content.
19+ // This includes imports and other top-level declarations that define component names.
20+ // We need to filter these out to avoid shadowing imported custom components.
21+ const moduleBindings = extractJsx ( ast ) ;
22+ const moduleEsmBindings = new Set ( moduleBindings . esmElements ) ;
23+
1724 const asides : Hast . ElementContent [ ] = [ ] ;
1825 visit ( ast , ( node , index , parent ) => {
1926 if ( ! isMdxJsxElementHast ( node ) || node . name !== "Aside" || index == null || parent == null ) {
@@ -47,7 +54,11 @@ export const rehypeExtractAsides: Unified.Plugin<[], Hast.Root> = () => {
4754 if ( ! jsxFragment || jsxFragment . type !== "JSXFragment" ) {
4855 throw new Error ( "No JSXFragment found" ) ;
4956 }
50- ast . children . push ( mdxJsEsmExport ( "Aside" , jsxFragment , extracted . jsxElements ) ) ;
57+ // Filter out JSX elements that are already defined at module scope (e.g., imported custom components).
58+ // This prevents the generated Aside component from shadowing these imports with undefined values
59+ // from useMDXComponents(), which would cause "Something went wrong!" errors.
60+ const jsxElementsToDestructure = extracted . jsxElements . filter ( ( name ) => ! moduleEsmBindings . has ( name ) ) ;
61+ ast . children . push ( mdxJsEsmExport ( "Aside" , jsxFragment , jsxElementsToDestructure ) ) ;
5162 } catch ( e ) {
5263 console . error ( String ( e ) ) ;
5364 }
0 commit comments