feat(nuxt): prefetch middleware/layouts + await layout loading (#10155)

This commit is contained in:
Sébastien Chopin 2023-01-19 14:01:21 +01:00 committed by GitHub
parent 49a2dd5d5a
commit 912eafbbf6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 2 deletions

View File

@ -140,8 +140,11 @@ export default defineNuxtModule({
addVitePlugin(PageMetaPlugin.vite(pageMetaOptions)) addVitePlugin(PageMetaPlugin.vite(pageMetaOptions))
addWebpackPlugin(PageMetaPlugin.webpack(pageMetaOptions)) addWebpackPlugin(PageMetaPlugin.webpack(pageMetaOptions))
// Add prefetching support for middleware & layouts
addPlugin(resolve(runtimeDir, 'plugins/prefetch.client'))
// Add router plugin // Add router plugin
addPlugin(resolve(runtimeDir, 'router')) addPlugin(resolve(runtimeDir, 'plugins/router'))
const getSources = (pages: NuxtPage[]): string[] => pages.flatMap(p => const getSources = (pages: NuxtPage[]): string[] => pages.flatMap(p =>
[relative(nuxt.options.srcDir, p.file), ...getSources(p.children || [])] [relative(nuxt.options.srcDir, p.file), ...getSources(p.children || [])]

View File

@ -0,0 +1,40 @@
import { hasProtocol } from 'ufo'
import { defineNuxtPlugin, useNuxtApp, useRouter } from '#app'
// @ts-ignore
import layouts from '#build/layouts'
// @ts-ignore
import { namedMiddleware } from '#build/middleware'
export default defineNuxtPlugin(() => {
const nuxtApp = useNuxtApp()
const router = useRouter()
// Force layout prefetch on route changes
nuxtApp.hooks.hook('app:mounted', () => {
router.beforeEach(async (to) => {
const layout = to?.meta?.layout
if (layout && typeof layouts[layout] === 'function') {
await layouts[layout]()
}
})
})
// Prefetch layouts & middleware
nuxtApp.hooks.hook('link:prefetch', (url) => {
if (hasProtocol(url)) { return }
const route = router.resolve(url)
if (!route) { return }
const layout = route?.meta?.layout
let middleware = Array.isArray(route?.meta?.middleware) ? route?.meta?.middleware : [route?.meta?.middleware]
middleware = middleware.filter(m => typeof m === 'string')
for (const name of middleware) {
if (typeof namedMiddleware[name] === 'function') {
namedMiddleware[name]()
}
}
if (layout && typeof layouts[layout] === 'function') {
layouts[layout]()
}
})
})

View File

@ -11,7 +11,7 @@ import {
} from 'vue-router' } from 'vue-router'
import { createError } from 'h3' import { createError } from 'h3'
import { withoutBase, isEqual } from 'ufo' import { withoutBase, isEqual } from 'ufo'
import type NuxtPage from './page' import type NuxtPage from '../page'
import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app' import { callWithNuxt, defineNuxtPlugin, useRuntimeConfig, showError, clearError, navigateTo, useError, useState } from '#app'
// @ts-ignore // @ts-ignore
import _routes from '#build/routes' import _routes from '#build/routes'