perf(kit): try non-subpath routes first to resolve nuxt modules (#31037)

This commit is contained in:
Harlan Wilton 2025-02-24 21:35:30 +11:00 committed by Daniel Roe
parent aac000061b
commit b7700f8614
No known key found for this signature in database
GPG Key ID: 3714AB03996F442B

View File

@ -93,6 +93,8 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n
const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias })
let resolvedNuxtModule: NuxtModule<any> | undefined
let hadNonFunctionPath = false
// Import if input is string
if (typeof nuxtModule === 'string') {
const paths = new Set<string>()
@ -102,9 +104,9 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n
nuxtModule = resolve(nuxt.options.rootDir, nuxtModule)
}
paths.add(join(nuxtModule, 'nuxt'))
paths.add(join(nuxtModule, 'module'))
paths.add(nuxtModule)
paths.add(join(nuxtModule, 'module'))
paths.add(join(nuxtModule, 'nuxt'))
for (const path of paths) {
try {
@ -114,9 +116,17 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n
url: nuxt.options.modulesDir.map(m => directoryToURL(m.replace(/\/node_modules\/?$/, '/'))),
extensions: nuxt.options.extensions,
})
nuxtModule = await jiti.import(src, { default: true }) as NuxtModule
resolvedModulePath = fileURLToPath(new URL(src))
if (!existsSync(resolvedModulePath)) {
continue
}
const instance = await jiti.import(src, { default: true }) as NuxtModule
// ignore possible barrel exports
if (typeof instance !== 'function') {
hadNonFunctionPath = true
continue
}
resolvedNuxtModule = instance
// nuxt-module-builder generates a module.json with metadata including the version
const moduleMetadataPath = new URL('module.json', src)
@ -141,17 +151,20 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n
throw error
}
}
} else {
resolvedNuxtModule = nuxtModule
}
// Throw error if module could not be found
if (typeof nuxtModule === 'string') {
throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`)
if (!resolvedNuxtModule) {
// Module was resolvable but returned a non-function
if (hadNonFunctionPath) {
throw new TypeError(`Nuxt module should be a function: ${nuxtModule}.`)
}
// Throw error if module could not be found
if (typeof nuxtModule === 'string') {
throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`)
}
}
// Throw error if input is not a function
if (typeof nuxtModule !== 'function') {
throw new TypeError('Nuxt module should be a function: ' + nuxtModule)
}
return { nuxtModule, buildTimeModuleMeta, resolvedModulePath } as { nuxtModule: NuxtModule<any>, buildTimeModuleMeta: ModuleMeta, resolvedModulePath?: string }
return { nuxtModule: resolvedNuxtModule, buildTimeModuleMeta, resolvedModulePath } as { nuxtModule: NuxtModule<any>, buildTimeModuleMeta: ModuleMeta, resolvedModulePath?: string }
}