@@ -17,13 +17,20 @@ export function createContextInjectionPlugin(): Plugin {
17
17
templateInitContext ,
18
18
templateInjectionMarker ,
19
19
]
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 ) } `
25
32
}
26
- else if ( matchScript && ! matchScript [ 2 ] ) {
33
+ else if ( ! setupScriptMatch && matchScripts . length === 1 ) {
27
34
// not a setup script
28
35
const matchExport = code . match ( / e x p o r t \s + d e f a u l t \s + \{ / )
29
36
if ( matchExport ) {
@@ -32,7 +39,7 @@ export function createContextInjectionPlugin(): Plugin {
32
39
let component = code . slice ( exportIndex )
33
40
component = component . slice ( 0 , component . indexOf ( '</script>' ) )
34
41
35
- const scriptIndex = ( matchScript . index || 0 ) + matchScript [ 0 ] . length
42
+ const scriptIndex = ( matchScripts [ 0 ] . index || 0 ) + matchScripts [ 0 ] [ 0 ] . length
36
43
const provideImport = '\nimport { injectionSlidevContext } from "@slidev/client/constants.ts"\n'
37
44
code = `${ code . slice ( 0 , scriptIndex ) } ${ provideImport } ${ code . slice ( scriptIndex ) } `
38
45
0 commit comments