Skip to content

Commit

Permalink
fix(nuxt): sort global middleware on layers, close nuxt#25891
Browse files Browse the repository at this point in the history
  • Loading branch information
markthree committed Feb 22, 2024
1 parent 6b50425 commit d173c61
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/nuxt/src/core/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import escapeRE from 'escape-string-regexp'
import { hash } from 'ohash'
import { camelCase } from 'scule'
import { filename } from 'pathe/utils'
import type { NuxtTemplate } from 'nuxt/schema'
import type { NuxtMiddleware, NuxtTemplate } from 'nuxt/schema'
import { annotatePlugins, checkForCircularDependencies } from './app'

export const vueShim: NuxtTemplate = {
Expand Down Expand Up @@ -208,14 +208,21 @@ export const layoutTemplate: NuxtTemplate = {
export const middlewareTemplate: NuxtTemplate = {
filename: 'middleware.mjs',
getContents ({ app }) {
const globalMiddleware = app.middleware.filter(mw => mw.global)
const globalMiddleware = sortGlobalMiddleware(app.middleware.filter(mw => mw.global))
const namedMiddleware = app.middleware.filter(mw => !mw.global)
const namedMiddlewareObject = genObjectFromRawEntries(namedMiddleware.map(mw => [mw.name, genDynamicImport(mw.path)]))

return [
...globalMiddleware.map(mw => genImport(mw.path, genSafeVariableName(mw.name))),
`export const globalMiddleware = ${genArrayFromRaw(globalMiddleware.map(mw => genSafeVariableName(mw.name)))}`,
`export const namedMiddleware = ${namedMiddlewareObject}`
].join('\n')
function sortGlobalMiddleware (globalMiddleware: NuxtMiddleware[]): NuxtMiddleware[] {
const reg = /^\d/
const withOrdergGobalMiddleware = globalMiddleware.filter(m => reg.test(m.name)).toSorted((l, r) => l.name > r.name ? 1 : -1)
const withoutOrdergGobalMiddleware = globalMiddleware.filter(m => !reg.test(m.name))
return [...withOrdergGobalMiddleware, ...withoutOrdergGobalMiddleware]
}
}
}

Expand Down

0 comments on commit d173c61

Please sign in to comment.