Skip to content

Commit 3064563

Browse files
committed
fix: ensure svelte virtual injection uses valid script tag
1 parent a7d1704 commit 3064563

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

src/index.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,19 @@ export const pluginTailwindCSS = (
181181
const importStr = `import "${pathToFileURL(VIRTUAL_UTILITIES_ID)}?${params.toString()}";\n`;
182182

183183
if (resourcePath.endsWith('.svelte')) {
184-
const scriptMatch = code.match(/<script[^>]*>/);
185-
if (scriptMatch && scriptMatch.index !== undefined) {
186-
const index = scriptMatch.index + scriptMatch[0].length;
184+
// Find the first <script> tag that is NOT inside a <svelte:head> or <svelte:options> tag etc.
185+
// By looking for `<script>` or `<script lang="ts">` at the start of a line or following generic HTML
186+
// Alternatively, simply look for the top-level <script> tag by avoiding those prefixed with <svelte:
187+
const scriptMatches = Array.from(code.matchAll(/<script[^>]*>/g));
188+
const topLevelScript = scriptMatches.find(
189+
(match) => {
190+
const textBefore = code.slice(0, match.index);
191+
return !textBefore.match(/<svelte:head>[\s\S]*$/);
192+
}
193+
);
194+
195+
if (topLevelScript && topLevelScript.index !== undefined) {
196+
const index = topLevelScript.index + topLevelScript[0].length;
187197
return `${code.slice(0, index)}\n${importStr}${code.slice(index)}`;
188198
}
189199
return `<script>\n${importStr}</script>\n${code}`;

0 commit comments

Comments
 (0)