Skip to content

Commit 5637013

Browse files
authored
fix: support multiple script in sfc (#2254)
1 parent 78a812b commit 5637013

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

packages/slidev/node/vite/contextInjection.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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(/<script((?!setup).)*(setup)?.*>/)
22-
if (matchScript && matchScript[2]) {
23-
// setup script
24-
return code.replace(/(<script.*>)/g, `$1\n${imports.join('\n')}\n`)
20+
21+
// Find all <script> blocks
22+
const matchScripts = [...code.matchAll(/<script([^>]*)>/g)]
23+
// Find the <script ... setup> block
24+
const setupScriptMatch = [...code.matchAll(/<script([^>]*)setup([^>]*)>/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(/export\s+default\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

Comments
 (0)