@@ -17,13 +17,20 @@ export function createContextInjectionPlugin(): Plugin {
1717 templateInitContext ,
1818 templateInjectionMarker ,
1919 ]
20- // eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/optimal-quantifier-concatenation
21- const matchScript = code . match ( / < s c r i p t ( (? ! s e t u p ) .) * ( s e t u p ) ? .* > / )
22- if ( matchScript && matchScript [ 2 ] ) {
23- // setup script
24- return code . replace ( / ( < s c r i p t .* > ) / g, `$1\n${ imports . join ( '\n' ) } \n` )
20+
21+ // Find all <script> blocks
22+ const matchScripts = [ ...code . matchAll ( / < s c r i p t ( [ ^ > ] * ) > / g) ]
23+ // Find the <script ... setup> block
24+ const setupScriptMatch = [ ...code . matchAll ( / < s c r i p t ( [ ^ > ] * ) s e t u p ( [ ^ > ] * ) > / g) ] . at ( 0 )
25+ if ( setupScriptMatch ) {
26+ // Only inject into the <script setup> block
27+ const setupTag = setupScriptMatch [ 0 ]
28+ const setupTagIndex = setupScriptMatch . index || 0
29+ const setupTagEnd = setupTagIndex + setupTag . length
30+ // Insert imports right after the <script setup ...> tag
31+ return `${ code . slice ( 0 , setupTagEnd ) } \n${ imports . join ( '\n' ) } \n${ code . slice ( setupTagEnd ) } `
2532 }
26- else if ( matchScript && ! matchScript [ 2 ] ) {
33+ else if ( ! setupScriptMatch && matchScripts . length === 1 ) {
2734 // not a setup script
2835 const matchExport = code . match ( / e x p o r t \s + d e f a u l t \s + \{ / )
2936 if ( matchExport ) {
@@ -32,7 +39,7 @@ export function createContextInjectionPlugin(): Plugin {
3239 let component = code . slice ( exportIndex )
3340 component = component . slice ( 0 , component . indexOf ( '</script>' ) )
3441
35- const scriptIndex = ( matchScript . index || 0 ) + matchScript [ 0 ] . length
42+ const scriptIndex = ( matchScripts [ 0 ] . index || 0 ) + matchScripts [ 0 ] [ 0 ] . length
3643 const provideImport = '\nimport { injectionSlidevContext } from "@slidev/client/constants.ts"\n'
3744 code = `${ code . slice ( 0 , scriptIndex ) } ${ provideImport } ${ code . slice ( scriptIndex ) } `
3845
0 commit comments