diff --git a/packages/nuxt/src/imports/module.ts b/packages/nuxt/src/imports/module.ts index 75f47d30b0..f42ccda04f 100644 --- a/packages/nuxt/src/imports/module.ts +++ b/packages/nuxt/src/imports/module.ts @@ -1,9 +1,10 @@ -import { addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, resolveAlias, updateTemplates, useNuxt } from '@nuxt/kit' +import { addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, resolveAlias, tryResolveModule, updateTemplates, useNuxt } from '@nuxt/kit' import { isAbsolute, join, normalize, relative, resolve } from 'pathe' import type { Import, Unimport } from 'unimport' import { createUnimport, scanDirExports } from 'unimport' import type { ImportPresetWithDeprecation, ImportsOptions } from 'nuxt/schema' +import { lookupNodeModuleSubpath, parseNodeModulePath } from 'mlly' import { TransformPlugin } from './transform' import { defaultPresets } from './presets' @@ -140,19 +141,29 @@ function addDeclarationTemplates (ctx: Unimport, options: Partial path.replace(/\.[a-z]+$/, '') - const resolved: Record = {} - const r = ({ from }: Import) => { - if (resolved[from]) { - return resolved[from] - } - let path = resolveAlias(from) - if (isAbsolute(path)) { - path = relative(join(nuxt.options.buildDir, 'types'), path) - } + const resolvedImportPathMap = new Map() + const r = ({ from }: Import) => resolvedImportPathMap.get(from) + async function cacheImportPaths (imports: Import[]) { + for (const i of imports) { + if (resolvedImportPathMap.has(i.from)) { continue } + let path = resolveAlias(i.from) + if (!isAbsolute(path)) { + path = await tryResolveModule(i.from, nuxt.options.modulesDir).then(async (r) => { + if (!r) { return r } - path = stripExtension(path) - resolved[from] = path - return path + const { dir, name } = parseNodeModulePath(r) + if (!dir || !name) { return r } + const subpath = await lookupNodeModuleSubpath(r) + return join(dir, name, subpath || '') + }) ?? path + } + if (isAbsolute(path)) { + path = relative(join(nuxt.options.buildDir, 'types'), path) + } + + path = stripExtension(path) + resolvedImportPathMap.set(i.from, path) + } } addTemplate({ @@ -162,10 +173,14 @@ function addDeclarationTemplates (ctx: Unimport, options: Partial '// Generated by auto imports\n' + ( - options.autoImport - ? await ctx.generateTypeDeclarations({ resolvePath: r }) - : '// Implicit auto importing is disabled, you can use explicitly import from `#imports` instead.' - ) + getContents: async () => { + const imports = await ctx.getImports().then(r => r.filter(i => !i.type)) + await cacheImportPaths(imports) + return '// Generated by auto imports\n' + ( + options.autoImport + ? await ctx.generateTypeDeclarations({ resolvePath: r }) + : '// Implicit auto importing is disabled, you can use explicitly import from `#imports` instead.' + ) + } }) }