fix(nuxt): async transform for inline middleware (#18460)

This commit is contained in:
Daniel Roe 2023-01-25 04:52:00 -08:00 committed by GitHub
parent 527dfbb5cf
commit 1d68b51c2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 14 additions and 5 deletions

View File

@ -80,8 +80,10 @@ async function initNuxt (nuxt: Nuxt) {
addWebpackPlugin(ImportProtectionPlugin.webpack(config))
// Add unctx transform
nuxt.hook('modules:done', () => {
addVitePlugin(UnctxTransformPlugin(nuxt).vite({ sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }))
addWebpackPlugin(UnctxTransformPlugin(nuxt).webpack({ sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }))
})
if (!nuxt.options.dev) {
const removeFromServer = ['onBeforeMount', 'onMounted', 'onBeforeUpdate', 'onRenderTracked', 'onRenderTriggered', 'onActivated', 'onDeactivated', 'onBeforeUnmount']

View File

@ -3,6 +3,8 @@ import { normalize } from 'pathe'
import { createTransformer } from 'unctx/transform'
import { createUnplugin } from 'unplugin'
const TRANSFORM_MARKER = '/* _processed_nuxt_unctx_transform */\n'
export const UnctxTransformPlugin = (nuxt: Nuxt) => {
const transformer = createTransformer({
asyncFunctions: ['defineNuxtPlugin', 'defineNuxtRouteMiddleware']
@ -15,14 +17,18 @@ export const UnctxTransformPlugin = (nuxt: Nuxt) => {
name: 'unctx:transform',
enforce: 'post',
transformInclude (id) {
if (id.includes('macro=true')) { return true }
id = normalize(id).replace(/\?.*$/, '')
return app?.plugins.some(i => i.src === id) || app?.middleware.some(m => m.path === id)
},
transform (code, id) {
// TODO: needed for webpack - update transform in unctx/unplugin?
if (code.startsWith(TRANSFORM_MARKER)) { return }
const result = transformer.transform(code)
if (result) {
return {
code: result.code,
code: TRANSFORM_MARKER + result.code,
map: options.sourcemap
? result.magicString.generateMap({ source: id, includeContent: true })
: undefined

View File

@ -4,8 +4,9 @@
<script setup>
definePageMeta({
middleware: () => {
middleware: defineNuxtRouteMiddleware(async () => {
await new Promise(resolve => setTimeout(resolve, 1))
return navigateTo({ path: '/' }, { redirectCode: 307 })
}
})
})
</script>