fix(nuxt): handle tsx code when extracting pageMeta/routeRules (#27583)

This commit is contained in:
Daniel Roe 2024-06-13 14:44:08 +01:00 committed by GitHub
parent d202669611
commit ab887d90d7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 21 additions and 8 deletions

View File

@ -18,11 +18,12 @@ export async function extractRouteRules (code: string): Promise<NitroRouteConfig
} }
if (!ROUTE_RULE_RE.test(code)) { return null } if (!ROUTE_RULE_RE.test(code)) { return null }
code = extractScriptContent(code) || code const script = extractScriptContent(code)
code = script?.code || code
let rule: NitroRouteConfig | null = null let rule: NitroRouteConfig | null = null
const js = await transform(code, { loader: 'ts' }) const js = await transform(code, { loader: script?.loader || 'ts' })
walk(parse(js.code, { walk(parse(js.code, {
sourceType: 'module', sourceType: 'module',
ecmaVersion: 'latest', ecmaVersion: 'latest',

View File

@ -154,12 +154,15 @@ export async function augmentPages (routes: NuxtPage[], vfs: Record<string, stri
return augmentedPages return augmentedPages
} }
const SFC_SCRIPT_RE = /<script[^>]*>([\s\S]*?)<\/script[^>]*>/i const SFC_SCRIPT_RE = /<script(?<attrs>[^>]*)>(?<content>[\s\S]*?)<\/script[^>]*>/i
export function extractScriptContent (html: string) { export function extractScriptContent (html: string) {
const match = html.match(SFC_SCRIPT_RE) const groups = html.match(SFC_SCRIPT_RE)?.groups || {}
if (match && match[1]) { if (groups.content) {
return match[1].trim() return {
loader: groups.attrs.includes('tsx') ? 'tsx' : 'ts',
code: groups.content.trim(),
} as const
} }
return null return null
@ -185,12 +188,12 @@ async function getRouteMeta (contents: string, absolutePath: string): Promise<Pa
return {} return {}
} }
if (!PAGE_META_RE.test(script)) { if (!PAGE_META_RE.test(script.code)) {
metaCache[absolutePath] = {} metaCache[absolutePath] = {}
return {} return {}
} }
const js = await transform(script, { loader: 'ts' }) const js = await transform(script.code, { loader: script.loader })
const ast = parse(js.code, { const ast = parse(js.code, {
sourceType: 'module', sourceType: 'module',
ecmaVersion: 'latest', ecmaVersion: 'latest',

View File

@ -0,0 +1,9 @@
<template>
<PageContent />
</template>
<script setup lang="tsx">
definePageMeta({})
defineRouteRules({})
const PageContent = () => (<div>Home Page</div>)
</script>