Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

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

Merged
merged 13 commits into from
Aug 23, 2022
Merged
24 changes: 24 additions & 0 deletions docs/content/3.api/1.composables/prefetch-components.md
Original file line number Diff line number Diff line change
@@ -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.
::
20 changes: 20 additions & 0 deletions docs/content/3.api/1.composables/preload-components.md
Original file line number Diff line number Diff line change
@@ -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.
::
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
33 changes: 33 additions & 0 deletions packages/nuxt/src/app/composables/preload.ts
Original file line number Diff line number Diff line change
@@ -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()
}
}
2 changes: 1 addition & 1 deletion packages/nuxt/src/components/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface ComponentsTemplateContext {
}

export type ImportMagicCommentsOptions = {
chunkName:string
chunkName: string
prefetch?: boolean | number
preload?: boolean | number
}
Expand Down
4 changes: 3 additions & 1 deletion packages/nuxt/src/imports/presets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ const appPreset = defineUnimportPreset({
'createError',
'defineNuxtLink',
'useAppConfig',
'defineAppConfig'
'defineAppConfig',
'preloadComponents',
'prefetchComponents'
]
})

Expand Down
6 changes: 6 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
9 changes: 9 additions & 0 deletions test/fixtures/basic/pages/prefetch/components.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script setup lang="ts">
await prefetchComponents('TestGlobal')
</script>

<template>
<div>
Testing prefetching global components
</div>
</template>