Skip to content

Commit

Permalink
fix: backport #18063, allow scanning exports from script module in …
Browse files Browse the repository at this point in the history
…svelte (#18077)

Co-authored-by: Paolo Ricciuti <[email protected]>
Co-authored-by: Ben McCann <[email protected]>
  • Loading branch information
3 people authored Sep 11, 2024
1 parent 8760293 commit d90ba40
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ export const commentRE = /<!--.*?-->/gs
const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
const svelteScriptModuleRE =
/\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i
const svelteModuleRE = /\smodule\b/i

function esbuildScanPlugin(
config: ResolvedConfig,
Expand Down Expand Up @@ -480,17 +482,28 @@ function esbuildScanPlugin(

const virtualModulePath = JSON.stringify(virtualModulePrefix + key)

const contextMatch = contextRE.exec(openTag)
const context =
contextMatch &&
(contextMatch[1] || contextMatch[2] || contextMatch[3])
let addedImport = false

// Especially for Svelte files, exports in <script context="module"> means module exports,
// For Svelte files, exports in <script context="module"> or <script module> means module exports,
// exports in <script> means component props. To avoid having two same export name from the
// star exports, we need to ignore exports in <script>
if (p.endsWith('.svelte') && context !== 'module') {
js += `import ${virtualModulePath}\n`
} else {
if (p.endsWith('.svelte')) {
let isModule = svelteModuleRE.test(openTag) // test for svelte5 <script module> syntax
if (!isModule) {
// fallback, test for svelte4 <script context="module"> syntax
const contextMatch = svelteScriptModuleRE.exec(openTag)
const context =
contextMatch &&
(contextMatch[1] || contextMatch[2] || contextMatch[3])
isModule = context === 'module'
}
if (!isModule) {
addedImport = true
js += `import ${virtualModulePath}\n`
}
}

if (!addedImport) {
js += `export * from ${virtualModulePath}\n`
}
}
Expand Down

0 comments on commit d90ba40

Please sign in to comment.