feat(nuxt): allow experimental global: 'sync' components (#22558)

This commit is contained in:
Daniel Roe 2023-08-09 12:19:00 +01:00 committed by GitHub
parent 396e538aad
commit b2cea4927e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 27 additions and 8 deletions

View File

@ -36,20 +36,25 @@ export default defineNuxtPlugin({
export const componentsPluginTemplate: NuxtPluginTemplate<ComponentsTemplateContext> = {
filename: 'components.plugin.mjs',
getContents ({ app }) {
const globalComponents = new Set<string>()
const lazyGlobalComponents = new Set<string>()
const syncGlobalComponents = new Set<string>()
for (const component of app.components) {
if (component.global) {
globalComponents.add(component.pascalName)
if (component.global === 'sync') {
syncGlobalComponents.add(component.pascalName)
} else if (component.global) {
lazyGlobalComponents.add(component.pascalName)
}
}
if (!globalComponents.size) { return emptyComponentsPlugin }
if (!lazyGlobalComponents.size && !syncGlobalComponents.size) { return emptyComponentsPlugin }
const components = [...globalComponents]
const lazyComponents = [...lazyGlobalComponents]
const syncComponents = [...syncGlobalComponents]
return `import { defineNuxtPlugin } from '#app/nuxt'
import { ${components.map(c => 'Lazy' + c).join(', ')} } from '#components'
import { ${[...lazyComponents.map(c => 'Lazy' + c), ...syncComponents].join(', ')} } from '#components'
const lazyGlobalComponents = [
${components.map(c => `["${c}", Lazy${c}]`).join(',\n')}
${lazyComponents.map(c => `["${c}", Lazy${c}]`).join(',\n')},
${syncComponents.map(c => `["${c}", ${c}]`).join(',\n')}
]
export default defineNuxtPlugin({

View File

@ -7,7 +7,7 @@ export interface Component {
chunkName: string
prefetch: boolean
preload: boolean
global?: boolean
global?: boolean | 'sync'
island?: boolean
mode?: 'client' | 'server' | 'all'
/**

View File

@ -94,6 +94,7 @@ describe('pages', () => {
// should register global components automatically
expect(html).toContain('global component registered automatically')
expect(html).toContain('global component via suffix')
expect(html).toContain('This is a synchronously registered global component')
await expectNoClientErrors('/')
})

View File

@ -0,0 +1,5 @@
<template>
<div>
This is a synchronously registered global component
</div>
</template>

View File

@ -146,6 +146,13 @@ export default defineNuxtConfig({
filePath: '~/other-components-folder/named-export'
})
},
'components:extend' (components) {
for (const comp of components) {
if (comp.pascalName === 'GlobalSync') {
comp.global = 'sync'
}
}
},
'vite:extendConfig' (config) {
config.plugins!.push({
name: 'nuxt:server',

View File

@ -44,6 +44,7 @@
</NuxtLink>
<NestedSugarCounter :multiplier="2" />
<CustomComponent />
<component :is="`global${'-'.toString()}sync`" />
<Spin>Test</Spin>
<component :is="`test${'-'.toString()}global`" />
<component :is="`with${'-'.toString()}suffix`" />