chore: update plugin sorting algorithm + update test

This commit is contained in:
userquin 2023-08-31 19:36:40 +02:00
parent 7ff5262be7
commit 3e83c09b97
2 changed files with 16 additions and 26 deletions

View File

@ -126,31 +126,21 @@ async function resolveApp (nuxt: Nuxt, app: NuxtApp) {
} }
// Re-initialise plugins // Re-initialise plugins
app.plugins = nuxt.options.plugins.map(normalizePlugin) app.plugins = []
let idx = 0
// Track scanned plugins separately so we can apply a sorting mechanism to them // Sort Plugins: layers plugins first then project plugins
const scannedPlugins: [string, NuxtPlugin][] = [] for (const config of nuxt.options._layers.map(layer => layer.config).reverse()) {
for (const config of nuxt.options._layers.map(layer => layer.config)) { app.plugins[idx++ === (nuxt.options._layers.length - 1) ? 'push' : 'unshift'](...[
for (const plugin of config.plugins || []) { ...(config.plugins || []),
app.plugins.push(normalizePlugin(plugin as NuxtPlugin | string)) ...config.srcDir
} ? await resolveFiles(config.srcDir, [
`${config.dir?.plugins || 'plugins'}/*.{ts,js,mjs,cjs,mts,cts}`,
if (config.srcDir) { `${config.dir?.plugins || 'plugins'}/*/index.*{ts,js,mjs,cjs,mts,cts}` // TODO: remove, only scan top-level plugins #18418
const pluginDir = join(config.srcDir, config.dir?.plugins || 'plugins') ])
for (const file of await resolveFiles(pluginDir, [ : []
'*.{ts,js,mjs,cjs,mts,cts}', ].map(plugin => normalizePlugin(plugin as NuxtPlugin)))
'*/index.*{ts,js,mjs,cjs,mts,cts}' // TODO: remove, only scan top-level plugins #18418
])) {
scannedPlugins.push([file.replace(pluginDir, ''), normalizePlugin(file)])
}
}
}
// Sort scanned plugins by their names so a scanned `01.plugin.ts` will always run before finished `02.plugin.ts`
// and append to the plugin array
for (const [_name, plugin] of scannedPlugins.sort(([a], [b]) => a.localeCompare(b))) {
app.plugins.push(plugin)
} }
app.plugins.unshift(...nuxt.options.plugins.map(normalizePlugin))
// Normalize and de-duplicate plugins and middleware // Normalize and de-duplicate plugins and middleware
app.middleware = uniqueBy(await resolvePaths(app.middleware, 'path'), 'name') app.middleware = uniqueBy(await resolvePaths(app.middleware, 'path'), 'name')

View File

@ -3,8 +3,8 @@ export default defineNuxtPlugin((nuxtApp) => {
if (!nuxtApp.$layerPluginPre) { if (!nuxtApp.$layerPluginPre) {
throw createError('layer plugin failed to run before end project plugin') throw createError('layer plugin failed to run before end project plugin')
} }
if (nuxtApp.$layerPluginPost) { if (!nuxtApp.$layerPluginPost) {
throw createError('layer plugin failed to run after end project plugin') throw createError('layer plugin failed to run before end project plugin')
} }
} }
}) })