Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: backport #18063, allow scanning exports from script module in svelte #18077

Merged
merged 1 commit into from
Sep 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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