fix(kit): support chainable extendRoutes in container (#1966)

This commit is contained in:
pooya parsa 2021-11-16 17:13:19 +01:00 committed by GitHub
parent 07ba36d721
commit 232fdd8cf3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 4 deletions

View File

@ -2,8 +2,7 @@ import { parse, relative } from 'pathe'
import consola from 'consola'
import type { Nuxt, NuxtPluginTemplate, NuxtTemplate } from '../types/nuxt'
import { chainFn } from '../utils/task'
import { resolveAlias } from '../utils/resolve'
import { addTemplate, addPluginTemplate, addServerMiddleware, extendPages } from './utils'
import { isNuxt2, addTemplate, addPluginTemplate, addServerMiddleware } from './utils'
import { installModule } from './install'
/** Legacy ModuleContainer for backwards compatibility with existing Nuxt 2 modules. */
@ -104,7 +103,16 @@ export function createModuleContainer (nuxt: Nuxt) {
/** Allows extending routes by chaining `options.build.extendRoutes` function. */
extendRoutes (fn) {
extendPages(routes => fn(routes, resolveAlias))
if (isNuxt2(nuxt)) {
nuxt.options.router.extendRoutes = chainFn(nuxt.options.router.extendRoutes, fn)
} else {
nuxt.hook('pages:extend', async (pages, ...args) => {
const maybeRoutes = await fn(pages, ...args)
if (maybeRoutes) {
console.warn('[kit] [compat] Using `extendRoutes` in Nuxt 3 needs to directly modify first argument instead of returning updated routes. Skipping extended routes.')
}
})
}
},
/** `requireModule` is a shortcut for `addModule` */

View File

@ -354,7 +354,11 @@ export function addComponent (opts: AddComponentOptions) {
export function extendPages (cb: NuxtHooks['pages:extend']) {
const nuxt = useNuxt()
nuxt.hook('pages:extend', cb)
if (isNuxt2(nuxt)) {
nuxt.hook('build:extendRoutes', cb)
} else {
nuxt.hook('pages:extend', cb)
}
}
const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"{(.+)}"/g, '$1')