feat(nuxt): allow programmatically prefetching global components (#6661)

Co-authored-by: Pooya Parsa <pooya@pi0.io>
This commit is contained in:
Daniel Roe 2022-08-23 20:12:22 +01:00 committed by GitHub
parent 1bce4df00a
commit f3499d788a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 97 additions and 2 deletions

View File

@ -0,0 +1,24 @@
# `prefetchComponents`
::StabilityEdge
::
Nuxt provides composables and utilities to give you fine-grained control over prefetching and preloading components.
> Prefetching component downloads the code in the background, this is based on the assumption that the component will likely be used for rendering, enabling the component to load instantly if and when the user requests it. The component is downloaded and cached for anticipated future use without the user making an explicit request for it.
You can use `prefetchComponents` to manually prefetch individual components that have been registered globally in your Nuxt app. (By default Nuxt registers these as async components.) You must use the Pascal-cased version of the component name.
```js
await prefetchComponents('MyGlobalComponent')
await prefetchComponents(['MyGlobalComponent1', 'MyGlobalComponent2'])
```
::alert{icon=👉}
Current implementation behaves exactly the same as [`preloadComponents`](/api/composables/preload-components) by preloading components instead of just prefetching we are working to improve this behavior.
::
::alert{icon=👉}
Currently, on server, `prefetchComponents` will have no effect.
::

View File

@ -0,0 +1,20 @@
# `preloadComponents`
::StabilityEdge
::
Nuxt provides composables and utilities to give you fine-grained control over prefetching and preloading components.
> Preloading components loads components that your page will need very soon, which you want to start loading early in rendering lifecycle. This ensures they are available earlier and are less likely to block the page's render, improving performance.
You can use `preloadComponents` to manually preload individual components that have been registered globally in your Nuxt app. (By default Nuxt registers these as async components.) You must use the Pascal-cased version of the component name.
```js
await preloadComponents('MyGlobalComponent')
await preloadComponents(['MyGlobalComponent1', 'MyGlobalComponent2'])
```
::alert{icon=👉}
Currently, on server, `preloadComponents` will have no effect.
::

View File

@ -12,3 +12,4 @@ export type { CookieOptions, CookieRef } from './cookie'
export { useRequestHeaders, useRequestEvent, setResponseStatus } from './ssr'
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, navigateTo, useRoute, useActiveRoute, useRouter } from './router'
export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router'
export { preloadComponents, prefetchComponents } from './preload'

View File

@ -0,0 +1,33 @@
import type { Component } from 'vue'
import { useNuxtApp } from '#app'
/**
* Preload a component or components that have been globally registered.
*
* @param components Pascal-cased name or names of components to prefetch
*/
export const preloadComponents = async (components: string | string[]) => {
if (process.server) { return }
const nuxtApp = useNuxtApp()
components = Array.isArray(components) ? components : [components]
await Promise.all(components.map(name => _loadAsyncComponent(nuxtApp.vueApp._context.components[name])))
}
/**
* Prefetch a component or components that have been globally registered.
*
* @param components Pascal-cased name or names of components to prefetch
*/
export const prefetchComponents = (components: string | string[]) => {
// TODO
return preloadComponents(components)
}
// --- Internal ---
function _loadAsyncComponent (component: Component) {
if ((component as any)?.__asyncLoader && !(component as any).__asyncResolved) {
return (component as any).__asyncLoader()
}
}

View File

@ -11,7 +11,7 @@ export interface ComponentsTemplateContext {
}
export type ImportMagicCommentsOptions = {
chunkName:string
chunkName: string
prefetch?: boolean | number
preload?: boolean | number
}

View File

@ -51,7 +51,9 @@ const appPreset = defineUnimportPreset({
'createError',
'defineNuxtLink',
'useAppConfig',
'defineAppConfig'
'defineAppConfig',
'preloadComponents',
'prefetchComponents'
]
})

View File

@ -360,6 +360,12 @@ describe('automatically keyed composables', () => {
})
})
describe('prefetching', () => {
it('should prefetch components', async () => {
await expectNoClientErrors('/prefetch/components')
})
})
if (process.env.NUXT_TEST_DEV) {
describe('detecting invalid root nodes', () => {
it('should detect invalid root nodes in pages', async () => {

View File

@ -0,0 +1,9 @@
<script setup lang="ts">
await prefetchComponents('TestGlobal')
</script>
<template>
<div>
Testing prefetching global components
</div>
</template>