fix(nuxt): use named import for lazy components (#25286)

This commit is contained in:
Becem 2024-01-19 22:43:19 +01:00 committed by GitHub
parent 648ef06993
commit 10af369436
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 66 additions and 1 deletions

View File

@ -74,7 +74,7 @@ export const loaderPlugin = createUnplugin((options: LoaderOptions) => {
if (lazy) {
imports.add(genImport('vue', [{ name: 'defineAsyncComponent', as: '__defineAsyncComponent' }]))
identifier += '_lazy'
imports.add(`const ${identifier} = __defineAsyncComponent(${genDynamicImport(component.filePath, { interopDefault: true })}${isClientOnly ? '.then(c => createClientOnly(c))' : ''})`)
imports.add(`const ${identifier} = __defineAsyncComponent(${genDynamicImport(component.filePath, { interopDefault: false })}.then(c => c.${component.export ?? 'default'} || c)${isClientOnly ? '.then(c => createClientOnly(c))' : ''})`)
} else {
imports.add(genImport(component.filePath, [{ name: component.export, as: identifier }]))

View File

@ -2306,3 +2306,23 @@ function normaliseIslandResult (result: NuxtIslandResponse) {
}
}
}
describe('lazy import components', () => {
let html = ''
it.sequential('fetch lazy-import-components page', async () => {
html = await $fetch('/lazy-import-components')
})
it('lazy load named component with mode all', () => {
expect(html).toContain('lazy-named-comp-all')
})
it('lazy load named component with mode client', () => {
expect(html).toContain('lazy-named-comp-client')
})
it('lazy load named component with mode server', () => {
expect(html).toContain('lazy-named-comp-server')
})
})

View File

@ -0,0 +1,31 @@
import { addComponent, createResolver, defineNuxtModule } from 'nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'lazy-import-components'
},
setup () {
const { resolve } = createResolver(import.meta.url)
addComponent({
name: 'NCompClient',
export: 'NComp',
filePath: resolve('./runtime/components'),
mode: 'client',
})
addComponent({
name: 'NCompServer',
export: 'NComp',
filePath: resolve('./runtime/components'),
mode: 'server',
})
addComponent({
name: 'NCompAll',
export: 'NComp',
filePath: resolve('./runtime/components'),
mode: 'all',
})
},
})

View File

@ -0,0 +1,7 @@
import { defineComponent, h } from 'vue'
export const NComp = defineComponent({
name: 'NComp',
props: { message: String },
render: (props: any) => h('h1', props.message),
})

View File

@ -0,0 +1,7 @@
<template>
<div>
<LazyNCompAll message="lazy-named-comp-all" />
<LazyNCompClient message="lazy-named-comp-client" />
<LazyNCompServer message="lazy-named-comp-server" />
</div>
</template>