feat(kit): load /module or /nuxt module subpath if it exists (#24707)

This commit is contained in:
Daniel Roe 2023-12-12 17:55:21 +00:00 committed by GitHub
parent 3991a10adf
commit 7827f1843b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 8 deletions

View File

@ -61,18 +61,28 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n
let buildTimeModuleMeta: ModuleMeta = {}
// Import if input is string
if (typeof nuxtModule === 'string') {
const src = await resolvePath(nuxtModule)
try {
const paths = [join(nuxtModule, 'nuxt'), join(nuxtModule, 'module'), nuxtModule]
let error: unknown
for (const path of paths) {
const src = await resolvePath(path)
// Prefer ESM resolution if possible
try {
nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })
} catch (error: unknown) {
logger.error(`Error while requiring module \`${nuxtModule}\`: ${error}`)
throw error
}
// nuxt-module-builder generates a module.json with metadata including the version
if (existsSync(join(dirname(src), 'module.json'))) {
buildTimeModuleMeta = JSON.parse(await fsp.readFile(join(dirname(src), 'module.json'), 'utf-8'))
}
break
} catch (_err: unknown) {
error = _err
continue
}
}
if (!nuxtModule && error) {
logger.error(`Error while requiring module \`${nuxtModule}\`: ${error}`)
throw error
}
}
// Throw error if input is not a function

View File

@ -0,0 +1 @@
export const someUtil = () => {}

View File

@ -0,0 +1,5 @@
import { defineNuxtModule } from 'nuxt/kit'
export default defineNuxtModule({
meta: { name: 'subpath' },
})

View File

@ -80,6 +80,7 @@ export default defineNuxtConfig({
}
},
modules: [
'~/modules/subpath',
'./modules/test',
'~/modules/example',
function (_, nuxt) {