Skip to content

Commit

Permalink
fix(nuxt): async transform for inline middleware (#18460)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Jan 25, 2023
1 parent 527dfbb commit 1d68b51
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
6 changes: 4 additions & 2 deletions packages/nuxt/src/core/nuxt.ts
Expand Up @@ -80,8 +80,10 @@ async function initNuxt (nuxt: Nuxt) {
addWebpackPlugin(ImportProtectionPlugin.webpack(config))

// Add unctx transform
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 }))
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']
Expand Down
8 changes: 7 additions & 1 deletion packages/nuxt/src/core/plugins/unctx.ts
Expand Up @@ -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']
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions test/fixtures/basic/pages/navigate-to-redirect.vue
Expand Up @@ -4,8 +4,9 @@

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

0 comments on commit 1d68b51

Please sign in to comment.