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 = {} let buildTimeModuleMeta: ModuleMeta = {}
// Import if input is string // Import if input is string
if (typeof nuxtModule === 'string') { if (typeof nuxtModule === 'string') {
const src = await resolvePath(nuxtModule) const paths = [join(nuxtModule, 'nuxt'), join(nuxtModule, 'module'), nuxtModule]
try { let error: unknown
for (const path of paths) {
const src = await resolvePath(path)
// Prefer ESM resolution if possible // Prefer ESM resolution if possible
nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir }) try {
} catch (error: unknown) { nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })
// 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}`) logger.error(`Error while requiring module \`${nuxtModule}\`: ${error}`)
throw 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'))
}
} }
// Throw error if input is not a function // 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: [
'~/modules/subpath',
'./modules/test', './modules/test',
'~/modules/example', '~/modules/example',
function (_, nuxt) { function (_, nuxt) {