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
app.plugins = nuxt.options.plugins.map(normalizePlugin)
// Track scanned plugins separately so we can apply a sorting mechanism to them
const scannedPlugins: [string, NuxtPlugin][] = []
for (const config of nuxt.options._layers.map(layer => layer.config)) {
for (const plugin of config.plugins || []) {
app.plugins.push(normalizePlugin(plugin as NuxtPlugin | string))
}
if (config.srcDir) {
const pluginDir = join(config.srcDir, config.dir?.plugins || 'plugins')
for (const file of await resolveFiles(pluginDir, [
'*.{ts,js,mjs,cjs,mts,cts}',
'*/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 = []
let idx = 0
// Sort Plugins: layers plugins first then project plugins
for (const config of nuxt.options._layers.map(layer => layer.config).reverse()) {
app.plugins[idx++ === (nuxt.options._layers.length - 1) ? 'push' : 'unshift'](...[
...(config.plugins || []),
...config.srcDir
? await resolveFiles(config.srcDir, [
`${config.dir?.plugins || 'plugins'}/*.{ts,js,mjs,cjs,mts,cts}`,
`${config.dir?.plugins || 'plugins'}/*/index.*{ts,js,mjs,cjs,mts,cts}` // TODO: remove, only scan top-level plugins #18418
])
: []
].map(plugin => normalizePlugin(plugin as NuxtPlugin)))
}
app.plugins.unshift(...nuxt.options.plugins.map(normalizePlugin))
// Normalize and de-duplicate plugins and middleware
app.middleware = uniqueBy(await resolvePaths(app.middleware, 'path'), 'name')

View File

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