fix(nuxt): don't append new route for redirect if one exists (#26368)

This commit is contained in:
Daniel Roe 2024-03-20 09:54:25 +00:00 committed by GitHub
parent 30d885248f
commit 4e6812d92c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 22 additions and 1 deletions

View File

@ -12,7 +12,7 @@ import type { EditableTreeNode, Options as TypedRouterOptions } from 'unplugin-v
import type { NitroRouteConfig } from 'nitropack'
import { defu } from 'defu'
import { distDir } from '../dirs'
import { normalizeRoutes, resolvePagesRoutes } from './utils'
import { normalizeRoutes, resolvePagesRoutes, resolveRoutePaths } from './utils'
import { extractRouteRules, getMappedPages } from './route-rules'
import type { PageMetaPluginOptions } from './plugins/page-meta'
import { PageMetaPlugin } from './plugins/page-meta'
@ -371,9 +371,13 @@ export default defineNuxtModule({
// when the app manifest is enabled.
nuxt.hook('pages:extend', (routes) => {
const nitro = useNitro()
let resolvedRoutes: string[]
for (const path in nitro.options.routeRules) {
const rule = nitro.options.routeRules[path]
if (!rule.redirect) { continue }
resolvedRoutes ||= routes.flatMap(route => resolveRoutePaths(route))
// skip if there's already a route matching this path
if (resolvedRoutes.includes(path)) { continue }
routes.push({
_sync: true,
path: path.replace(/\/[^/]*\*\*/, '/:pathMatch(.*)'),

View File

@ -539,3 +539,10 @@ export function pathToNitroGlob (path: string) {
return path.replace(/\/(?:[^:/]+)?:\w+.*$/, '/**')
}
export function resolveRoutePaths (page: NuxtPage, parent = '/'): string[] {
return [
joinURL(parent, page.path),
...page.children?.flatMap(child => resolveRoutePaths(child, joinURL(parent, page.path))) || []
]
}

View File

@ -30,6 +30,11 @@ export default defineNuxtConfig({
val: 1
}
},
routeRules: {
'/param': {
redirect: '/param/1'
}
},
modules: [
function () {
addTypeTemplate({

View File

@ -0,0 +1,5 @@
<template>
<div>
<!-- -->
</div>
</template>