@@ -89,6 +89,47 @@ function addNextEmptyElementToEntry(content: string) {
8989 return s . toString ( ) ;
9090}
9191
92+ function addImportToEntry ( content : string , webComponentNpmPath : string ) {
93+ let hasAddedImport = false ;
94+ const s = new MagicString ( content ) ;
95+
96+ const ast = parse ( content , {
97+ babelrc : false ,
98+ comments : true ,
99+ configFile : false ,
100+ plugins : [
101+ importMetaPlugin ,
102+ [ tsPlugin , { isTSX : true , allowExtensions : true } ] ,
103+ [ proposalDecorators , { legacy : true } ] ,
104+ ] ,
105+ } ) ;
106+
107+ traverse ( ast ! , {
108+ enter ( { node } : any ) {
109+ if ( hasAddedImport ) {
110+ return ;
111+ }
112+ if (
113+ node . type === 'Directive' &&
114+ node . value . type === 'DirectiveLiteral' &&
115+ node . value . value === 'use client'
116+ ) {
117+ s . prependRight (
118+ node . end ,
119+ `import ${ NextEmptyElementName } from '${ webComponentNpmPath } ';`
120+ ) ;
121+ hasAddedImport = true ;
122+ }
123+ } ,
124+ } ) ;
125+
126+ if ( hasAddedImport ) {
127+ return s . toString ( ) ;
128+ } else {
129+ return `import ${ NextEmptyElementName } from '${ webComponentNpmPath } ';${ s . toString ( ) } ` ;
130+ }
131+ }
132+
92133export function getWebComponentCode ( options : CodeOptions , port : number ) {
93134 const {
94135 hotKeys = [ 'shiftKey' , 'altKey' ] ,
@@ -280,7 +321,7 @@ export async function getCodeWithWebComponent({
280321 ) ;
281322 if ( ! file . match ( webComponentNpmPath ) ) {
282323 if ( isNextjs ) {
283- code = `import ${ NextEmptyElementName } from ' ${ webComponentNpmPath } ';\n ${ code } ` ;
324+ code = addImportToEntry ( code , webComponentNpmPath ) ;
284325 code = addNextEmptyElementToEntry ( code ) ;
285326 } else {
286327 code = `import '${ webComponentNpmPath } ';${ code } ` ;
0 commit comments