From a929a91d71a07cfd4292702f1c8f820b9475ba38 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 5 Nov 2024 17:53:42 +0000 Subject: [PATCH] fix(kit): use `mlly` to resolve module paths to avoid cjs fallback (#29799) --- packages/kit/src/module/install.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/kit/src/module/install.ts b/packages/kit/src/module/install.ts index b489970172..c6df75807e 100644 --- a/packages/kit/src/module/install.ts +++ b/packages/kit/src/module/install.ts @@ -1,11 +1,13 @@ import { existsSync, promises as fsp, lstatSync } from 'node:fs' +import { pathToFileURL } from 'node:url' import type { ModuleMeta, Nuxt, NuxtConfig, NuxtModule } from '@nuxt/schema' import { dirname, isAbsolute, join, resolve } from 'pathe' import { defu } from 'defu' import { createJiti } from 'jiti' +import { resolve as resolveModule } from 'mlly' import { isNuxt2 } from '../compatibility' import { useNuxt } from '../context' -import { resolveAlias } from '../resolve' +import { resolveAlias, resolvePath } from '../resolve' import { logger } from '../logger' const NODE_MODULES_RE = /[/\\]node_modules[/\\]/ @@ -83,11 +85,14 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n // Import if input is string if (typeof nuxtModule === 'string') { const paths = [join(nuxtModule, 'nuxt'), join(nuxtModule, 'module'), nuxtModule, join(nuxt.options.rootDir, nuxtModule)] - - for (const parentURL of nuxt.options.modulesDir) { - for (const path of paths) { + for (const path of paths) { + for (const parentURL of nuxt.options.modulesDir) { try { - const src = jiti.esmResolve(path, { parentURL: parentURL.replace(/\/node_modules\/?$/, '') }) + const resolved = resolveAlias(path, nuxt.options.alias) + const src = isAbsolute(resolved) + ? await resolvePath(resolved, { cwd: parentURL, fallbackToOriginal: false, extensions: nuxt.options.extensions }) + : await resolveModule(resolved, { url: pathToFileURL(parentURL.replace(/\/node_modules\/?$/, '')), extensions: nuxt.options.extensions }) + nuxtModule = await jiti.import(src, { default: true }) as NuxtModule // nuxt-module-builder generates a module.json with metadata including the version @@ -98,7 +103,7 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n break } catch (error: unknown) { const code = (error as Error & { code?: string }).code - if (code === 'MODULE_NOT_FOUND' || code === 'ERR_PACKAGE_PATH_NOT_EXPORTED' || code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT') { + if (code === 'MODULE_NOT_FOUND' || code === 'ERR_PACKAGE_PATH_NOT_EXPORTED' || code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT' || code === 'ENOTDIR') { continue } logger.error(`Error while importing module \`${nuxtModule}\`: ${error}`)