feat(nuxt): transform setup within defineComponent options (#24515)

This commit is contained in:
Daniel Roe 2023-12-14 21:00:36 +00:00 committed by GitHub
parent 109ee082a5
commit db3a9f0554
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 50 additions and 12 deletions

View File

@ -1,9 +1,11 @@
// @ts-expect-error withAsyncContext is internal API // @ts-expect-error withAsyncContext is internal API
import { getCurrentInstance, withAsyncContext as withVueAsyncContext } from 'vue' import { getCurrentInstance, withAsyncContext as withVueAsyncContext } from 'vue'
export function withAsyncContext (fn: () => PromiseLike<unknown>) { export function withNuxtContext <T>(fn: () => T) {
return withVueAsyncContext(() => { const nuxtApp = getCurrentInstance()?.appContext.app.$nuxt
const nuxtApp = getCurrentInstance()?.appContext.app.$nuxt return nuxtApp ? nuxtApp.runWithContext(fn) : fn()
return nuxtApp ? nuxtApp.runWithContext(fn) : fn() }
})
export function withAsyncContext (fn: () => PromiseLike<unknown>) {
return withVueAsyncContext(() => withNuxtContext(fn))
} }

View File

@ -1,8 +1,9 @@
import { getCurrentInstance, reactive, toRefs } from 'vue' import { defineComponent as _defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
import type { DefineComponent, defineComponent } from 'vue' import type { ComponentOptions, DefineComponent } from 'vue'
import { useHead } from '@unhead/vue' import { useHead } from '@unhead/vue'
import type { NuxtApp } from '../nuxt' import type { NuxtApp } from '../nuxt'
import { useNuxtApp } from '../nuxt' import { useNuxtApp } from '../nuxt'
import { withNuxtContext } from './asyncContext'
import { useAsyncData } from './asyncData' import { useAsyncData } from './asyncData'
import { useRoute } from './router' import { useRoute } from './router'
import { createError } from './error' import { createError } from './error'
@ -28,7 +29,7 @@ async function runLegacyAsyncData (res: Record<string, any> | Promise<Record<str
} }
/*@__NO_SIDE_EFFECTS__*/ /*@__NO_SIDE_EFFECTS__*/
export const defineNuxtComponent: typeof defineComponent = export const defineNuxtComponent: typeof _defineComponent =
function defineNuxtComponent (...args: any[]): any { function defineNuxtComponent (...args: any[]): any {
const [options, key] = args const [options, key] = args
const { setup } = options const { setup } = options
@ -68,3 +69,18 @@ export const defineNuxtComponent: typeof defineComponent =
} }
} as DefineComponent } as DefineComponent
} }
export const defineComponent: typeof _defineComponent = (arg1: Function | Record<string, any>, arg2?: Partial<ComponentOptions>) => {
if (typeof arg1 === 'function') {
return _defineComponent((...args) => withNuxtContext(() => arg1(...args)), arg2)
}
if (arg1.setup) {
return _defineComponent({
...arg1,
setup: (...args: any[]) => withNuxtContext(() => arg1.setup(...args))
}) as any
}
return _defineComponent(arg1)
}

View File

@ -30,7 +30,7 @@ const granularAppPresets: InlinePreset[] = [
from: '#app/config' from: '#app/config'
}, },
{ {
imports: ['defineNuxtComponent'], imports: ['defineComponent', 'defineNuxtComponent'],
from: '#app/composables/component' from: '#app/composables/component'
}, },
{ {
@ -156,7 +156,6 @@ const vuePreset = defineUnimportPreset({
'onScopeDispose', 'onScopeDispose',
// Component // Component
'defineComponent',
'defineAsyncComponent', 'defineAsyncComponent',
'resolveComponent', 'resolveComponent',
'getCurrentInstance', 'getCurrentInstance',

View File

@ -81,6 +81,8 @@ describe('imports:nuxt', () => {
}) })
const excludedVueHelpers = [ const excludedVueHelpers = [
// Nuxt stub for this helper
'defineComponent',
// Already globally registered // Already globally registered
'defineEmits', 'defineEmits',
'defineExpose', 'defineExpose',

View File

@ -189,6 +189,7 @@ export default defineUntypedSchema({
asyncTransforms: { asyncTransforms: {
asyncFunctions: ['defineNuxtPlugin', 'defineNuxtRouteMiddleware'], asyncFunctions: ['defineNuxtPlugin', 'defineNuxtRouteMiddleware'],
objectDefinitions: { objectDefinitions: {
defineComponent: ['setup'],
defineNuxtComponent: ['asyncData', 'setup'], defineNuxtComponent: ['asyncData', 'setup'],
defineNuxtPlugin: ['setup'], defineNuxtPlugin: ['setup'],
definePageMeta: ['middleware', 'validate'] definePageMeta: ['middleware', 'validate']

View File

@ -1951,10 +1951,14 @@ describe.skipIf(isDev() || isWindows || !isRenderingJson)('payload rendering', (
}) })
}) })
describe.skipIf(process.env.TEST_CONTEXT !== 'async')('Async context', () => { describe('Async context', () => {
it('should be available', async () => { it.skipIf(process.env.TEST_CONTEXT !== 'async')('should be available', async () => {
expect(await $fetch('/async-context')).toContain('&quot;hasApp&quot;: true') expect(await $fetch('/async-context')).toContain('&quot;hasApp&quot;: true')
}) })
it('should transform `setup` within defineComponent', async () => {
const html = await $fetch('/async-transform-component')
expect(html).toContain('using automatic `setup` async transform')
})
}) })
describe.skipIf(isWindows)('useAsyncData', () => { describe.skipIf(isWindows)('useAsyncData', () => {

View File

@ -0,0 +1,14 @@
<script>
export default defineComponent({
async setup () {
await nextTick()
useRuntimeConfig()
}
})
</script>
<template>
<div>
should not error out when using automatic `setup` async transform
</div>
</template>