Skip to content

Commit d90ba40

Browse files
patak-devpaoloricciutibenmccann
authored
fix: backport #18063, allow scanning exports from script module in svelte (#18077)
Co-authored-by: Paolo Ricciuti <[email protected]> Co-authored-by: Ben McCann <[email protected]>
1 parent 8760293 commit d90ba40

File tree

1 file changed

+22
-9
lines changed
  • packages/vite/src/node/optimizer

1 file changed

+22
-9
lines changed

packages/vite/src/node/optimizer/scan.ts

+22-9
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,9 @@ export const commentRE = /<!--.*?-->/gs
284284
const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
285285
const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
286286
const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
287-
const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
287+
const svelteScriptModuleRE =
288+
/\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
289+
const svelteModuleRE = /\smodule\b/i
288290

289291
function esbuildScanPlugin(
290292
config: ResolvedConfig,
@@ -480,17 +482,28 @@ function esbuildScanPlugin(
480482

481483
const virtualModulePath = JSON.stringify(virtualModulePrefix + key)
482484

483-
const contextMatch = contextRE.exec(openTag)
484-
const context =
485-
contextMatch &&
486-
(contextMatch[1] || contextMatch[2] || contextMatch[3])
485+
let addedImport = false
487486

488-
// Especially for Svelte files, exports in <script context="module"> means module exports,
487+
// For Svelte files, exports in <script context="module"> or <script module> means module exports,
489488
// exports in <script> means component props. To avoid having two same export name from the
490489
// star exports, we need to ignore exports in <script>
491-
if (p.endsWith('.svelte') && context !== 'module') {
492-
js += `import ${virtualModulePath}\n`
493-
} else {
490+
if (p.endsWith('.svelte')) {
491+
let isModule = svelteModuleRE.test(openTag) // test for svelte5 <script module> syntax
492+
if (!isModule) {
493+
// fallback, test for svelte4 <script context="module"> syntax
494+
const contextMatch = svelteScriptModuleRE.exec(openTag)
495+
const context =
496+
contextMatch &&
497+
(contextMatch[1] || contextMatch[2] || contextMatch[3])
498+
isModule = context === 'module'
499+
}
500+
if (!isModule) {
501+
addedImport = true
502+
js += `import ${virtualModulePath}\n`
503+
}
504+
}
505+
506+
if (!addedImport) {
494507
js += `export * from ${virtualModulePath}\n`
495508
}
496509
}

0 commit comments

Comments
 (0)